绑定UpdateSourceTrigger =在程序启动时明确,更新源 [英] Binding UpdateSourceTrigger=Explicit, updates source at program startup

查看:238
本文介绍了绑定UpdateSourceTrigger =在程序启动时明确,更新源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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();
    }
}

我要更新,只有当Enter键在文本框中pssed $ P $来源。这工作得很好。然而,在程序启动时绑定更新源。我怎样才能避免这种情况?我缺少的东西吗?

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?

推荐答案

的问题是,数据绑定是在显示(中和的InitializeComponent电话解决,但是这不是对你很重要,因为在这一点上你的DataContext是没有设置)。我不认为你可以prevent这一点,但我有一个变通的想法:

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:

不要设置在DataContext你调用Show()之前。你可以做到这一点(例如)是这样的:

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

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

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

这篇关于绑定UpdateSourceTrigger =在程序启动时明确,更新源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆