Sunday, April 13, 2008 8:12 PM
Tamir Khason
Quick WPF Tip: Change as you type in WPF when binded to the same DependencyProperty
Let’s write this simple code:
<TextBox Name="source"/>
<TextBlock Text="{Binding ElementName=source, Path=Text}"/>
Now, the value of TextBlock will be changed during typing in TextBlock. However, let bind both to some DependencyProperty
<TextBox Text="{Binding Path=SomeProp}"/>
<TextBlock Text="{Binding Path=SomeProp}"/>
Now, TextBlock will be updated only when you leave TextBox. Why this happens? It’s because by default UpdateSourceTrigger property of Binding set to LostFocus, when binded to DepndencyObject.
So, how to fix it? Simple set UpdateSourceTrigger explicitly.
<TextBox Text="{Binding Path=SomeProp, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Text="{Binding Path=SomeProp, UpdateSourceTrigger=PropertyChanged}"/>
Hurah, the value of the TextBlock (as well as the value of underlying dependency property) changing while typing into TextBox.
Have a nice day.
תגים:WPF, Tips and Tricks, .NET 3.5