Force binding to update when Command is triggered

binding, command, mvvm, wpf

Solution

I have solved this now by explicitely setting the focus to some other element before asking for the values. This obviously makes the element that currently has the focus lose it and update the binding.

To set the focus, I have written an attached property, inspired by answers on other questions. Also, together with my other question I made this somewhat automated.

So to use it, I basically attach my property to an element, in this case a tab control:

<TabControl c:Util.ShouldFocus="{Binding ShouldClearFocus}">

In my view model, I have a simple boolean property `ShouldClearFocus` that is a standard property raising a `PropertyChangedEvent`, so data binding works. Then I simply set `ShouldClearFocus` to `true` when I want to reset the focus. The attached property automatically sets the focus and resets the property value again. That way I can keep setting `ShouldClearFocus` without having to set it to `false` in between.

The attached property is a standard implementation with this as its change handler:

public static void ShouldFocusChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    if (!(bool)e.NewValue || !(obj is FrameworkElement))
        return;

    FrameworkElement element = (FrameworkElement)obj;
    if (element.Focusable)
        element.Focus();

    // reset value
    BindingExpression bindingExpression = BindingOperations.GetBindingExpression(obj, ShouldFocusProperty);
    if (bindingExpression != null)
    {
        PropertyInfo property = bindingExpression.DataItem.GetType().GetProperty(bindingExpression.ParentBinding.Path.Path);
        if (property != null)
            property.SetValue(bindingExpression.DataItem, false, null);
    }
    else
        SetShouldFocus(obj, false);
}

Problem

is there a way to update a binding before or when a command is triggered? I have some text fields I can edit and save using a command, accessible via a keyboard shortcut. As the binding is usually only updated when the text field loses focus, the last change is not kept when pressing the key to save the data. Instead I have to tab out of the text field first to make it update and then save it. Is there a way to force the update in an elegant way? I am using MVVM (but not any MVVM framework), so I’d like to keep UI specific things out of the command code. Also I don’t really want to change the binding to update on every change, it’s fine to have it update only when the focus is lost.

Original source

Related problems