Thursday, December 15, 2011

Solution to a problem in Application Bar and Binding on the same page

Just a quick share of a useful code I found in MSDN forums for when application bar button invokes the event handler before binding on the current element takes place.
The problem is that if you add a textbox to the page and then user presses a button on the application bar, then if user presses that button just after filling that textbox, then unexpectedly you will not receive the updated value for that textbox's binding target, whatever the reason is the solution for this is to update binding manually knowing the fact that the textbox is the current focused control, here is the code:

public static class Utilities
{
    public static void MakeSureBindingsApplied()
    {
        var focusObj = FocusManager.GetFocusedElement() as TextBox;
        if (focusObj != null)
        {
            var binding = focusObj.GetBindingExpression(TextBox.TextProperty);
            binding.UpdateSource();
        }
    }
}

Then what you have to do is just to call it in the event handler for application bar button, make sure that you call this method before reading data from binding's targets.

private void saveButton_Click(object sender, System.EventArgs e)
{
    Utilities.MakeSureBindingsApplied();
}


No comments:

Post a Comment