Wednesday, September 22, 2010

Windows Phone 7 Quick Tip #7 – Be Aware-of and Know the work around for a Data Binding bug in RTM tools

There is a bug in the final build of the development tools for Windows Phone 7 where if you have a two-way bound TextBox in focus, and you immediately click on an ApplicationBarIconButton, the property bound with that TextBox in focus won’t get updated before the ApplicationBarIconButton event handler.  Obviously if your handler does something like persist the values from the form, this could be a real problem.  If you use a <Button> Click event handler, you are fine, the property update will take place.

Here’s a simple work-around (that I received from the grape-vine, so if you were the original creator, please let me know so I can give credit where credit is due):

Create a static method on your application class:

        public static void BindCurrentTextBox()

    {

       var textBox = FocusManager.GetFocusedElement() as TextBox;
       if (textBox != null)
       {
          var binding = textBox.GetBindingExpression(TextBox.TextProperty);
          if(binding != null)
              binding.UpdateSource();
       }
    }

 

Then right before you do something from the ApplicationBarIconButton click event, call this static method.

Not pretty, but not all-that-bad of a work-around.

-twb

2 comments:

  1. That came in handy for me. You can extend that code to also handle PasswordBox as it has the same problem.

    -dave

    ReplyDelete
  2. Coding4Fun tools have added a propepty UpdateSourceOnChange that you can set on the textbox xaml. No need for any code.

    ReplyDelete