Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextBox Binding TwoWay Doesn't Update Until Focus Lost WP7

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?

like image 736
Josh Close Avatar asked Apr 06 '11 16:04

Josh Close


2 Answers

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:

object focusObj = FocusManager.GetFocusedElement(); if (focusObj != null && focusObj is TextBox) {     var binding = (focusObj as TextBox).GetBindingExpression(TextBox.TextProperty);     binding.UpdateSource(); } 
like image 51
Stefan Wick MSFT Avatar answered Oct 12 '22 01:10

Stefan Wick MSFT


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 the Binding to Explicit. Then, in the TextBox's TextChanged callback, update the Binding source.

like image 30
Praetorian Avatar answered Oct 12 '22 01:10

Praetorian