Hitesh P
Hitesh P

Reputation: 416

How to control when TextBox Text as binding source updates the target value?

Trying for a simple thing. I want TextBlock text to be updated to what TextBox's text value is. However, I want it to happen only on LostFocus. Currently below code updates a TextBlock as user is typing into a TextBox. How do we achieve that?

<StackPanel>
    <TextBox x:Name="txtQty" />
    <TextBlock Text="{Binding ElementName=txtQty, Path=Text}" />
</StackPanel>

I explored the UpdateSourceTrigger property on textbox with LostFocus, but it won't work as that controls how the source should be updated, whereas here I need how the destination updates.

I prefer to have a XAML only solution.

Upvotes: 2

Views: 749

Answers (2)

Mardukar
Mardukar

Reputation: 435

As others already said, the best way would be to bind the TextBlock and the TextBox to the same viewmodel property.

If you want to do it only with XAML code you could try it from the other side and bind your TextBox to the TextBlock. Like this:

<StackPanel>
    <TextBox  Text="{Binding ElementName=txtQty, Path=Text, UpdateSourceTrigger=LostFocus, Mode=OneWayToSource}" />
    <TextBlock x:Name="txtQty" />
</StackPanel>

Upvotes: 1

mm8
mm8

Reputation: 169200

XAML is a markup language.

The straight-forward way to to this would be to bind the TextBox and the TextBlock to the same view model source property. The source property will be set when the TextBox loses focus and then the TextBlock will then be updated provided that the view model class implements the INotifyPropertyChanged interface as expected.

You could of course also handle the LostKeyboardFocus event for the TextBox and set the Text property of the TextBlock programmatically in the code-behind of the view. This approach is not any worse than trying to implement some logic in the XAML markup of the very same view. Just because you possibly can do something in pure XAML, it doesn't mean that you always should. A programming language such as C# usually does a better job implementing some logic.

Upvotes: 2

Related Questions