Binding UpdateSourceTrigger = Explicit, update source at program startup

I have the 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 the source only when the Enter key is pressed in the text box. It works great. However, the binding of the update source at program startup. How can i avoid this? Did I miss something?

+6
explicit wpf binding
source share
2 answers

The problem is that DataBinding is allowed when calling Show (and on InitializeComponent, but that is not important to you, because at that moment your DataContext is not set yet). I don't think you can prevent this, but I have an idea for a workaround:

Do not set the DataContext before calling Show (). You can achieve this (for example) as follows:

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

Change the binding by default

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

All Articles