绑定UpdateSourceTrigger = Explicit,在程序启动时更新源

问题描述 投票:6回答:2

我有以下代码:

<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();
    }
}

我想只在文本框中按下“Enter”键时更新源。这很好用。但是在程序启动时绑定更新源。我怎么能避免这个?我错过了什么吗?

wpf binding explicit updatesourcetrigger
2个回答
0
投票

问题是,DataBinding是在Show(和InitializeComponent)的调用上解析的,但这对你来说并不重要,因为此时你的DataContext还没有设置好。我认为你不能阻止这种情况,但我有一个解决方法的想法:

在调用Show()之前不要设置DataContext。你可以像这样实现这个(例如):

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

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

和:

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

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

-2
投票

将绑定模式更改为默认值

<TextBox Text="{Binding Path=Name, 
                    Mode=Default, 
                    UpdateSourceTrigger=Explicit, 
                    FallbackValue=default text}" 
        KeyUp="TextBox_KeyUp" 
        x:Name="textBox1"/>
© www.soinside.com 2019 - 2024. All rights reserved.