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);
}