WP7 Tip - Binding Issues When Switching Pages Via Application Bar

28 November 2011

Binding in WP7 is awesome - you pay a little bit of upfront plumbing / set up / development time, and everything just works together super nice. But sometimes, it doesn't quite go to plan, and one example I came across recently was a page where I had multiple TextBox controls with two way bindings to a view model. Most of it worked properly, but if you entered a text box, inputted some text and then use the Application Bar to switch pages while still having the keyboard up, the content of the control wasn't being applied to the model.

A bit of google shows that the reason this happens is because updates to objects via binding only get called when the TextBox loses focus - and when you switch pages while the keyboard is still open on a TextBox, it still has focus (and therefore the binding isn't updated). Initially, I calling the focus method on a different control on the page (in the same way you would when hiding the SIP), but stepping through the code showed that the bindings were still not updated.

It turns out that the real fix for this issue is to update the binding manually after the application bar event is raised, which you can do using the following example code:

    private void AppBarIcon_Click(object sender, EventArgs e)
    {
        //apply the bindings if clicking directly on appbar - see http://social.msdn.microsoft.com/Forums/en/windowsphone7series/thread/c0ce4e48-6d5c-42d7-bc14-f412f1e0762c            
        object focusObj = FocusManager.GetFocusedElement();
        if (focusObj != null && focusObj is TextBox)
        {
            var binding = (focusObj as TextBox).GetBindingExpression(TextBox.TextProperty);
            binding.UpdateSource();
        }

        NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));           
    }

Thanks to this thread on MSDN for the help :)

Tags: application bar, navigation, binding, wp7

Add a Comment

No Comments