WP7 Does Not Update Binding Until Control Has Lost Focus

I was Using MVVM in one of my applications and came across a problem. I had a page bound to an object in the ViewModel and an ApplicationBarIconButton which allows you to save the item to Isolated Storage. The problem though is when you tap on the Application bar Icon it does not trigged the Lost Focus event of the last Test Box you had typed into. This means that the last field does not get updated in your data source. After some investigation it looks like WPF resolves this issue by setting the UpdarteSourceTrigger to PropertyChanged. Sadly Silverlight for WP7 (and I think Silverlight) does not support this feature. After some digging I found a solution that is a bit of a hack but resolves the issue.

  1. Set the UpdateSourceTrigger to Explicit

    <TextBox x:Name=”Title” Text=”{Binding Path=Title, Mode=TwoWay, UpdateSourceTrigger=Explicit}”/>

     

  2. Add an event handler to for the TextChanged Event. I used a generic name so it can be used by other text boxes

    <TextBox x:Name=”Title” Text=”{Binding Path=Title, Mode=TwoWay, UpdateSourceTrigger=Explicit}” TextChanged=”TextBox_TextChanged” />

     

  3. Add the following code to the Event Handler to manually update the binding.

     

This forces the binding to be updated when the text is changed in the textbox every time you type or delete a character. If you’re binding to a remote source be careful this doesn’t product an overhead and slow your application down.

Advertisements
  1. #1 by Neil Bryson on September 27, 2011 - 12:27 pm

    Exactly what I was looking for. Thanks a bunch 🙂

  2. #2 by Frederick Chapleau (@fchapleau) on January 16, 2012 - 6:04 pm

    Solved my problem! I’ve worked a little on it to be compatible with PasswordBox and CheckBox etc Checkout http://www.chapleau.info/blog/2012/01/15/WP7BindingLostFocusWorkaround.html
    Thanks!

  3. #3 by Pauli Kettunen on April 18, 2013 - 2:31 pm

    Thanks mate, I had a similar problem and your solution solved it 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: