<p>In my WPF application, I have a number of databound TextBoxes. The <code>UpdateSourceTrigger</code> for these bindings is <code>LostFocus</code>. The object is saved using the File menu. The problem I have is that it is possible to enter a new value into a TextBox, select Save from the File menu, and never persist the new value (the one visible in the TextBox) because accessing the menu does not remove focus from the TextBox. How can I fix this? Is there some way to force all the controls in a page to databind?</p>

<p><em>@palehorse: Good point. Unfortunately, I need to use LostFocus as my UpdateSourceTrigger in order to support the type of validation I want.</em></p>

<p><em>@dmo: I had thought of that. It seems, however, like a really inelegant solution for a relatively simple problem. Also, it requires that there be some control on the page which is is always visible to receive the focus. My application is tabbed, however, so no such control readily presents itself.</em></p>

<p><em>@Nidonocu: The fact that using the menu did not move focus from the TextBox confused me as well. That is, however, the behavior I am seeing. The following simple example demonstrates my problem:</em></p>

<pre class="lang-xml prettyprint-override"><code>&lt;Window x:Class="WpfApplication2.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"&gt;
    &lt;Window.Resources&gt;
        &lt;ObjectDataProvider x:Key="MyItemProvider" /&gt;
    &lt;/Window.Resources&gt;
    &lt;DockPanel LastChildFill="True"&gt;
        &lt;Menu DockPanel.Dock="Top"&gt;
            &lt;MenuItem Header="File"&gt;
                &lt;MenuItem Header="Save" Click="MenuItem_Click" /&gt;
            &lt;/MenuItem&gt;
        &lt;/Menu&gt;
        &lt;StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}"&gt;
            &lt;Label Content="Enter some text and then File &gt; Save:" /&gt;
            &lt;TextBox Text="{Binding ValueA}" /&gt;
            &lt;TextBox Text="{Binding ValueB}" /&gt;
        &lt;/StackPanel&gt;
    &lt;/DockPanel&gt;
&lt;/Window&gt;
</code></pre>

<pre><code>using System;
using System.Text;
using System.Windows;
using System.Windows.Data;

namespace WpfApplication2
{
    public partial class Window1 : Window
    {
        public MyItem Item
        {
            get { return (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance as MyItem; }
            set { (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance = value; }
        }

        public Window1()
        {
            InitializeComponent();
            Item = new MyItem();
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(string.Format("At the time of saving, the values in the TextBoxes are:\n'{0}'\nand\n'{1}'", Item.ValueA, Item.ValueB));
        }
    }

    public class MyItem
    {
        public string ValueA { get; set; }
        public string ValueB { get; set; }
    }
}
</code></pre>

[{'answer_id': 57506, 'author': 'palehorse', 'author_id': 312, 'author_profile': 'https://Stackoverflow.com/users/312', 'pm_score': 2, 'selected': False, 'text': '<p>Have you tried setting the UpdateSourceTrigger to PropertyChanged?  Alternatively, you could call the UpdateSOurce() method, but that seems like a bit overkill and defeats the purpose of TwoWay databinding.</p>\n'}, {'answer_id': 57662, 'author': 'dmo', 'author_id': 1807, 'author_profile': 'https://Stackoverflow.com/users/1807', 'pm_score': 1, 'selected': False, 'text': '<p>Could you set the focus somewhere else just before saving?</p>\n\n<p>You can do this by calling focus() on a UI element.</p>\n\n<p>You could focus on whatever element invokes the "save".  If your trigger is LostFocus then you have to move the focus somewhere.  Save has the advantage that it isn\'t modified and would make sense to the user.</p>\n'}, {'answer_id': 58443, 'author': 'rudigrobler', 'author_id': 5147, 'author_profile': 'https://Stackoverflow.com/users/5147', 'pm_score': 4, 'selected': True, 'text': '<blockquote>\n<p>Suppose you have a TextBox in a window, and a ToolBar with a Save button in it. Assume the TextBox’s Text property is bound to a property on a business object, and the binding’s UpdateSourceTrigger property is set to the default value of LostFocus, meaning that the bound value is pushed back to the business object property when the TextBox loses input focus. Also, assume that the ToolBar’s Save button has its Command property set to ApplicationCommands.Save command.</p>\n<p>In that situation, if you edit the TextBox and click the Save button with the mouse, there is a problem. When clicking on a Button in a ToolBar, the TextBox does not lose focus. Since the TextBox’s LostFocus event does not fire, the Text property binding does not update the source property of the business object.</p>\n<p>Obviously you should not validate and save an object if the most recently edited value in the UI has not yet been pushed into the object. This is the exact problem Karl had worked around, by writing code in his window that manually looked for a TextBox with focus and updated the source of the data binding. His solution worked fine, but it got me thinking about a generic solution that would also be useful outside of this particular scenario. Enter CommandGroup…</p>\n</blockquote>\n<p>Taken from Josh Smith’s CodeProject article about <a href="http://www.codeproject.com/KB/WPF/commandgroup.aspx" rel="noreferrer">CommandGroup</a></p>\n'}, {'answer_id': 58451, 'author': 'rudigrobler', 'author_id': 5147, 'author_profile': 'https://Stackoverflow.com/users/5147', 'pm_score': 3, 'selected': False, 'text': '<p>This is a UGLY hack but should also work</p>\n\n<pre><code>TextBox focusedTextBox = Keyboard.FocusedElement as TextBox;\nif (focusedTextBox != null)\n{\n    focusedTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();\n}\n</code></pre>\n\n<p>This code checks if a TextBox has focus... If 1 is found... update the binding source!</p>\n'}, {'answer_id': 229738, 'author': 'Sam', 'author_id': 7021, 'author_profile': 'https://Stackoverflow.com/users/7021', 'pm_score': 0, 'selected': False, 'text': '<p>The easiest way is to <em>set the focus somewhere</em>.<br>\nYou can set the focus back immediately, but setting the focus anywhere will trigger the LostFocus-Event on <strong>any type of control</strong> and make it update its stuff:</p>\n\n<pre><code>IInputElement x = System.Windows.Input.Keyboard.FocusedElement;\nDummyField.Focus();\nx.Focus();\n</code></pre>\n\n<p>Another way would be to get the focused element, get the binding element from the focused element, and trigger the update manually. An example for TextBox and ComboBox (you would need to add any control type you need to support):</p>\n\n<pre><code>TextBox t = Keyboard.FocusedElement as TextBox;\nif ((t != null) &amp;&amp; (t.GetBindingExpression(TextBox.TextProperty) != null))\n  t.GetBindingExpression(TextBox.TextProperty).UpdateSource();\n\nComboBox c = Keyboard.FocusedElement as ComboBox;\nif ((c != null) &amp;&amp; (c.GetBindingExpression(ComboBox.TextProperty) != null))\n  c.GetBindingExpression(ComboBox.TextProperty).UpdateSource();\n</code></pre>\n'}, {'answer_id': 1764845, 'author': 'BigBlondeViking', 'author_id': 119910, 'author_profile': 'https://Stackoverflow.com/users/119910', 'pm_score': 5, 'selected': False, 'text': '<p>I found that removing the menu items that are scope depended from the FocusScope of the menu causes the textbox to lose focus correctly. I wouldn\'t think this applies to ALL items in Menu, but certainly for a save or validate action.</p>\n\n<pre><code>&lt;Menu FocusManager.IsFocusScope="False" &gt;\n</code></pre>\n'}, {'answer_id': 4724766, 'author': 'Dave the Rave', 'author_id': 580011, 'author_profile': 'https://Stackoverflow.com/users/580011', 'pm_score': 4, 'selected': False, 'text': '<p>Assuming that there is more than one control in the tab sequence, the following solution appears to be complete and general (just cut-and-paste)...</p>\n\n<pre><code>Control currentControl = System.Windows.Input.Keyboard.FocusedElement as Control;\n\nif (currentControl != null)\n{\n    // Force focus away from the current control to update its binding source.\n    currentControl.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));\n    currentControl.Focus();\n}\n</code></pre>\n'}, {'answer_id': 6195116, 'author': 'Shawn Nelson', 'author_id': 437254, 'author_profile': 'https://Stackoverflow.com/users/437254', 'pm_score': 0, 'selected': False, 'text': '<p>What do you think about this?  I believe I\'ve figured out a way to make it a bit more generic using reflection.  I really didn\'t like the idea of maintaining a list like some of the other examples.</p>\n\n<pre><code>var currentControl = System.Windows.Input.Keyboard.FocusedElement;\nif (currentControl != null)\n{\n    Type type = currentControl.GetType();\n    if (type.GetMethod("MoveFocus") != null &amp;&amp; type.GetMethod("Focus") != null)\n    {\n        try\n        {\n            type.GetMethod("MoveFocus").Invoke(currentControl, new object[] { new TraversalRequest(FocusNavigationDirection.Next) });\n            type.GetMethod("Focus").Invoke(currentControl, null);\n        }\n        catch (Exception ex)\n        {\n            throw new Exception("Unable to handle unknown type: " + type.Name, ex);\n        }\n    }\n}\n</code></pre>\n\n<p>See any problems with that?</p>\n'}, {'answer_id': 7518908, 'author': 'Ram', 'author_id': 959677, 'author_profile': 'https://Stackoverflow.com/users/959677', 'pm_score': 2, 'selected': False, 'text': '<p>Simple solution is update the Xaml code as shown below</p>\n\n<pre><code>    &lt;StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}"&gt; \n        &lt;Label Content="Enter some text and then File &gt; Save:" /&gt; \n        &lt;TextBox Text="{Binding ValueA, UpdateSourceTrigger=PropertyChanged}" /&gt; \n        &lt;TextBox Text="{Binding ValueB, UpdateSourceTrigger=PropertyChanged}" /&gt; \n    &lt;/StackPanel&gt; \n</code></pre>\n'}, {'answer_id': 8680327, 'author': 'Nathan Swannet', 'author_id': 983690, 'author_profile': 'https://Stackoverflow.com/users/983690', 'pm_score': 1, 'selected': False, 'text': '<p>Since I noticed this issue is still a pain in the ass to solve on a very generic way, I tried various solutions.</p>\n\n<p>Eventually one that worked out for me:\nWhenever the need is there that UI changes must be validated and updated to its sources (Check for changes upon closeing a window, performing Save operations, ...), I call a validation function which does various things:\n- make sure a focused element (like textbox, combobox, ...) loses its focus which will trigger default updatesource behavior\n- validate any controls within the tree of the DependencyObject which is given to the validation function\n- set focus back to the original focused element</p>\n\n<p>The function itself returns true if everything is in order (validation is succesful) -> your original action (closeing with optional asking confirmation, saveing, ...) can continue. Otherwise the function will return false and your action cannot continue because there are validation errors on one or more elements (with the help of a generic ErrorTemplate on the elements).</p>\n\n<p>The code (validation functionality is based on the article <a href="https://stackoverflow.com/questions/127477/detecting-wpf-validation-errors">Detecting WPF Validation Errors</a>):</p>\n\n<pre><code>public static class Validator\n{\n    private static Dictionary&lt;String, List&lt;DependencyProperty&gt;&gt; gdicCachedDependencyProperties = new Dictionary&lt;String, List&lt;DependencyProperty&gt;&gt;();\n\n    public static Boolean IsValid(DependencyObject Parent)\n    {\n        // Move focus and reset it to update bindings which or otherwise not processed until losefocus\n        IInputElement lfocusedElement = Keyboard.FocusedElement;\n        if (lfocusedElement != null &amp;&amp; lfocusedElement is UIElement)\n        {\n            // Move to previous AND to next InputElement (if your next InputElement is a menu, focus will not be lost -&gt; therefor move in both directions)\n            (lfocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));\n            (lfocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));\n            Keyboard.ClearFocus();\n        }\n\n        if (Parent as UIElement == null || (Parent as UIElement).Visibility != Visibility.Visible)\n            return true;\n\n        // Validate all the bindings on the parent \n        Boolean lblnIsValid = true;\n        foreach (DependencyProperty aDependencyProperty in GetAllDependencyProperties(Parent))\n        {\n            if (BindingOperations.IsDataBound(Parent, aDependencyProperty))\n            {\n                // Get the binding expression base. This way all kinds of bindings (MultiBinding, PropertyBinding, ...) can be updated\n                BindingExpressionBase lbindingExpressionBase = BindingOperations.GetBindingExpressionBase(Parent, aDependencyProperty);\n                if (lbindingExpressionBase != null)\n                {\n                    lbindingExpressionBase.ValidateWithoutUpdate();\n                    if (lbindingExpressionBase.HasError)\n                        lblnIsValid = false;\n                }\n            }\n        }\n\n        if (Parent is Visual || Parent is Visual3D)\n        {\n            // Fetch the visual children (in case of templated content, the LogicalTreeHelper will return no childs)\n            Int32 lintVisualChildCount = VisualTreeHelper.GetChildrenCount(Parent);\n            for (Int32 lintVisualChildIndex = 0; lintVisualChildIndex &lt; lintVisualChildCount; lintVisualChildIndex++)\n                if (!IsValid(VisualTreeHelper.GetChild(Parent, lintVisualChildIndex)))\n                    lblnIsValid = false;\n        }\n\n        if (lfocusedElement != null)\n            lfocusedElement.Focus();\n\n        return lblnIsValid;\n    }\n\n    public static List&lt;DependencyProperty&gt; GetAllDependencyProperties(DependencyObject DependencyObject)\n    {\n        Type ltype = DependencyObject.GetType();\n        if (gdicCachedDependencyProperties.ContainsKey(ltype.FullName))\n            return gdicCachedDependencyProperties[ltype.FullName];\n\n        List&lt;DependencyProperty&gt; llstDependencyProperties = new List&lt;DependencyProperty&gt;();\n        List&lt;FieldInfo&gt; llstFieldInfos = ltype.GetFields(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Static).Where(Field =&gt; Field.FieldType == typeof(DependencyProperty)).ToList();\n        foreach (FieldInfo aFieldInfo in llstFieldInfos)\n            llstDependencyProperties.Add(aFieldInfo.GetValue(null) as DependencyProperty);\n        gdicCachedDependencyProperties.Add(ltype.FullName, llstDependencyProperties);\n\n        return llstDependencyProperties;\n    }\n}\n</code></pre>\n'}, {'answer_id': 9840108, 'author': 'Tomer', 'author_id': 805138, 'author_profile': 'https://Stackoverflow.com/users/805138', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve run into this issue and the best solution I\'ve found was to change the focusable value of the button (or any other component such as MenuItem) to true:</p>\n\n<pre><code>&lt;Button Focusable="True" Command="{Binding CustomSaveCommand}"/&gt;\n</code></pre>\n\n<p>The reason it works, is because it forces the button to get focused before it invokes the command and therefore makes the TextBox <strong>or any other UIElement for that matter</strong> to loose their focus and raise lost focus event which invokes the binding to be changed.</p>\n\n<p><em>In case you are using bounded command (as I was pointing to in my example), John Smith\'s great solution won\'t fit very well since you can\'t bind StaticExtension into bounded property (nor DP).</em></p>\n'}, {'answer_id': 26902637, 'author': 'kenjiuno', 'author_id': 974413, 'author_profile': 'https://Stackoverflow.com/users/974413', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m using BindingGroup.</p>\n\n<p>XAML:</p>\n\n<pre><code>&lt;R:RibbonWindow Closing="RibbonWindow_Closing" ...&gt;\n\n    &lt;FrameworkElement.BindingGroup&gt;\n        &lt;BindingGroup /&gt;\n    &lt;/FrameworkElement.BindingGroup&gt;\n\n    ...\n&lt;/R:RibbonWindow&gt;\n</code></pre>\n\n<p>C#</p>\n\n<pre><code>private void RibbonWindow_Closing(object sender, CancelEventArgs e) {\n    e.Cancel = !NeedSave();\n}\n\nbool NeedSave() {\n    BindingGroup.CommitEdit();\n\n    // Insert your business code to check modifications.\n\n    // return true; if Saved/DontSave/NotChanged\n    // return false; if Cancel\n}\n</code></pre>\n\n<p>It should work.</p>\n'}]
['https://Stackoverflow.com/questions/57493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/317/']