Binding UpdateSourceTrigger=Explicit, updates source at program startup

我的梦境 提交于 2019-12-10 13:36:38

问题


I have following code:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
    <TextBox Text="{Binding Path=Name, 
                            Mode=OneWayToSource, 
                            UpdateSourceTrigger=Explicit, 
                            FallbackValue=default text}" 
             KeyUp="TextBox_KeyUp" 
             x:Name="textBox1"/>
</Grid>

    public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void TextBox_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            BindingExpression exp = this.textBox1.GetBindingExpression(TextBox.TextProperty);
            exp.UpdateSource();
        }
    }
}



    public class ViewModel
{
    public string Name
    {
        set
        {
            Debug.WriteLine("setting name: " + value);
        }
    }
}



    public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        Window1 window = new Window1();
        window.DataContext = new ViewModel();
        window.Show();
    }
}

I want to update source only when "Enter" key is pressed in textbox. This works fine. However binding updates source at program startup. How can I avoid this? Am I missing something?


回答1:


The problem is, that DataBinding is resolved on the call of Show (and on InitializeComponent, but that is not important for you, because at that point your DataContext is not set yet). I don't think you can prevent that, but I have an idea for a workaround:

Do not set the DataContext before you call Show(). You can achieve this (for example) like this:

public partial class Window1 : Window
{
    public Window1(object dataContext)
    {
        InitializeComponent();

        this.Loaded += (sender, e) =>
        {
            DataContext = dataContext;
        };
    }
}

and:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    Window1 window = new Window1(new ViewModel());
    window.Show();
}



回答2:


Change your Binding Mode to Default

<TextBox Text="{Binding Path=Name, 
                    Mode=Default, 
                    UpdateSourceTrigger=Explicit, 
                    FallbackValue=default text}" 
        KeyUp="TextBox_KeyUp" 
        x:Name="textBox1"/>


来源:https://stackoverflow.com/questions/1516588/binding-updatesourcetrigger-explicit-updates-source-at-program-startup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!