I’ve got two text boxes txt1 and txt2 and a string dependency property sprop.
public static readonly DependencyProperty spropProperty = DependencyProperty.Register("sprop", typeof (string), typeof (MainWindow), new UIPropertyMetadata(string.Empty));
public string sprop
{
get { return (string) this.GetValue(spropProperty); }
set { this.SetValue(spropProperty, value); }
}
Now, if I set data binding in XAML for txt1 this way:
Text="{Binding sprop, ElementName=window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}
txt1 updates sprop instantaneously, whenever the text box text is changed.
But if I set data binding in C# for txt2 this way:
DataContext = this;
txt2.SetBinding(TextBox.TextProperty, "sprop");
then txt2 updates sprop only when it loses focus.
How can I update sprop as soon as txt2‘s text changes using C# code?
What I have tried:
DataContext = this;
var myBinding = new Binding("sprop");
myBinding.Source = this;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
txt2.SetBinding(TextBlock.TextProperty, myBinding);
You need to also set the UpdateSourceTrigger in your txt2 in order to get updated once property changed, which you can also set in code: