Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two way databinding from TextBox doesn't update when button in ApplicationBar is clicked

I have a TextBox in my app, and an ApplicationBarIconButton in the ApplicationBar which acts as a "submit" for the contents of the TextBox.

When editing the TextBox using the virtual keyboard, the ApplicationBarIconButton is still visible below the SIP, so you can submit straight away without dismissing the keyboard: nice!

However, when clicking the button, the viewmodel to which the TextBox is bound does not update.

I found someone else with the same problem here, and they have used the pretty nasty workaround of manually updating the viewmodel on the TextBox's TextChanged event.

Removes all the elegance of using databound view models!

Is this a bug in WP7?

Or is there a nicer way around this that I haven't found yet?

like image 742
funkybro Avatar asked Dec 10 '22 04:12

funkybro


1 Answers

The problem is that silverlight bindings do not support the PropertyChanged value for UpdateSourceTrigger. This means that by default a TextBox will update the property bound to Text when the TextBox loses focus and the only other possibility is to update it explicitly in code as is done in the example from your link.

You only really have two options here: Update the binding when the button is clicked or remove focus from the TextBox when the button is clicked.

I usually update the binding on the TextChanged event. I use an extension method to do this:

public static void UpdateBinding(this TextBox textBox)
{
    BindingExpression bindingExpression = 
            textBox.GetBindingExpression(TextBox.TextProperty);
    if (bindingExpression != null)
    {
            bindingExpression.UpdateSource();
    }
}

allowing me to just call this in code behind:

textBox.UpdateBinding();

You may also be able to use a custom behaviour for this.

like image 89
calum Avatar answered May 29 '23 09:05

calum