I have a page with some text boxes for data input. The binding of the text box is set to TwoWay
. The data in my view model only gets updated if the text box loses focus. If I click a button, such as save, and the text box still has the focus, the changes in the text box aren't changed in my view model on the save event.
Is there a way to have the binding save the value of the text box before it loses focus? Or do I need to do something in the save event?
Download Charles Petzold's free book Programming Windows Phone 7. On page 387 he talks about how to do this.
Basically, set the
UpdateSourceTrigger
property of theBinding
toExplicit
. Then, in theTextBox
'sTextChanged
callback, update the Binding source.I assume your Save button is an ApplicationBarButton (not a normal button). For normal buttons it will just work because they take focus and hence the data-binding will kick in.
For ApplicationBarButtons on the phone it's a little different because they don't take focus away from the client app. To ensure the data-binding kicks in when your Save button is clicked, you can add the following code in your handler:
You can use the
UpdateTextBindingOnPropertyChanged
behavior from the Prism Library for WP7 to update the bound value when the text changes instead of on lost focus.This link has a solution that worked perfectly in WinRT. He inherits TextBox and adds a new property: BindableText.
http://www.familie-smits.com/post/2012/07/29/UpdateSourceTrigger-in-WinRT.aspx
I'm going in the opposite direction of @Praetorian.
Your
TextBox
has a defaultUpdateSourceTrigger
value ofLostFocus
. This means the value is only pushed to your ViewModel property when.. it loses focus.You can set the UpdateSourceTrigger to PropertyChanged:
From http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx:
Keep in mind this means that anything that is trigger by an update to this property will happen much more frequently (basically with every keypress, instead of a single "flush" when the
TextBox
loses focus).Hope that helps!
Here's a quick access answer to the Microsoft solution suggested by Derek. Rather than downloading and sifting through all the Prism stuff, just copy this class into your project then follow the steps afterwards to activate it:
UpdateBindingOnPropertyChangedBehviour.cs
This is basically a cleaned-up version of the Microsoft Prism 4.1 code (see the Silverlight\Prism.Interactivity project if you want to browse the rest).
Now how to use it:
Inside the XAML of each TextBox to which you want to apply the bahvior (which already has a TwoWay binding to your source property), add the following:
<i:Interaction.Behaviors>
<my:UpdateTextBindingOnPropertyChanged />
</i:Interaction.Behaviors>
Note: the "my:" prefix may be different in your code. It's just the namespace reference where you added the behaviour class.