On a Windows Phone application and if you are using a two way binding along with Application Bar Button or Menu, you might be having a nightmare that the binding for the last focused control is not happening when you click the application bar button or menu.
Now let’s have a look why this happens. If you take any Windows Phone control (Button in the below figure), it is a proper silverlight control and if you are looking at the ApplicationBarIconButton / ApplicationBarMenuItem, it is totally from a different planet “Microsoft.Phone.Shell” and therefore it is not going to interact with the Silverlight controls as other silverlight controls. And whenever, the application bar icon button or menu icon is clicked, the focus will still remain inside the text box. This leads to the scenario where the control in which you have the focus will never fire the PropertyChanged. This behavior of the control is by design.
Now let’s focus on the resolution part. Adding of the below code snippet into the click event of the ApplicationBarIconButton or ApplicationBarMenuItem will solve the problem. Essentially the code below will solve the problem if you have all the controls as TextBox and you have a Text property bind to the source. Add appropriate statements for different controls. Say if you have ListBox control also in your page and it has the source bound to a SelectedItem, then you will need to add another condition checking for the ListBox control and triggering the source for SelectedItemProperty.
// Get the element from which the focus is var control = FocusManager.GetFocusedElement(); // Check the control type if (control != null && control.GetType() == typeof(TextBox)) { ((TextBox)control).GetBindingExpression(TextBox.TextProperty).UpdateSource(); } // If there are multiple type of controls on the page with binding add other types also as elseif
Thanks to Stefan Wick (Microsoft) for providing this solution.