Reputation: 3417
I was wondering if it is possible to change the time that a binding updates the controls that are bound to it. For instance, I'm working with a TextBox, which is updating every time a key is pressed, but I would like it to update when it loses focus instead.
Any ideas?
Upvotes: 0
Views: 80
Reputation: 189535
Well this surprises me because I thought the TextBox was the one control which held back its updating of the binding source until the focused moved elsewhere, a small test confirms this.
Anyhow, lets imagine that it does normally update on every key press or some control like it does.
A general solution would be to take "manual" control of source updating. You can do this with the UpdateSourceTrigger
property setting to "Explicit". This means the source of the binding will only by updated when your code explicitly calls the UpdateSource
method on the BindingExpression
for the binding with the TextProperty
of the "TextBox".
You could perform this explicit update then in an event handler for the "TextBox" LostFocus
event.
For Example, in an initial UserControl add this xaml:-
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox x:Name="Target" />
<TextBox x:Name="Source" Grid.Row="1"
Text="{Binding Text, ElementName=Target, Mode=TwoWay, UpdateSourceTrigger=Explicit}" LostFocus="Source_LostFocus"/>
</Grid>
Now in the code-behind the event handler looks like this:-
private void Source_LostFocus(object sender, RoutedEventArgs e)
{
((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
Upvotes: 2
Reputation: 4122
Not sure if this is exactly what you're trying to do, but here's a suggestion:
Remove the binding and then add an event for your textbox for LostFocus: ie.
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
textBox.Text = originallyBindedValue;
}
Not as clean as through XAML but you should be able to get your desired behavior.
Upvotes: 1