【问题标题】:Binding UpdateSourceTrigger=Explicit, updates source at program startupBinding UpdateSourceTrigger=Explicit,在程序启动时更新源
【发布时间】:2010-12-03 17:56:47
【问题描述】:

我有以下代码:

<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


    【解决方案1】:

    问题是,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"/>
      

      【讨论】:

      • 这有什么帮助?
      猜你喜欢
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多