在这种情况下,文本框实际上并没有失去逻辑焦点,因此永远不会引发事件 - 本质上我实际上想要的是LostKeyboardFocus
事件,而不是LostFocus
触发更新的事件。
This issue is similar to WPF: Data bound TabControl doesn't commit changes when new tab is selected and there is a Microsoft connect item for it here with a number of potential solutions, however I fixed this using an attached property like so.
public static readonly DependencyProperty BindOnLostKeyboardFocusProperty =
DependencyProperty.RegisterAttached("BindOnLostKeyboardFocus", typeof(bool), typeof(MainWindow), new PropertyMetadata(default(bool), BindOnLostKeyboardFocusChanged));
private static void BindOnLostKeyboardFocusChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var control = o as UIElement;
if (control != null)
{
if ((bool) e.NewValue)
{
control.AddHandler(LostKeyboardFocusEvent, new RoutedEventHandler(ControlLostKeyboardFocus));
}
else
{
control.RemoveHandler(LostKeyboardFocusEvent, new RoutedEventHandler(ControlLostKeyboardFocus));
}
}
}
private static void ControlLostKeyboardFocus(object sender, RoutedEventArgs e)
{
var control = (UIElement)sender;
control.RaiseEvent(new RoutedEventArgs(LostFocusEvent));
}
这只是意味着无论何时LostKeyboardFocus
为该控件引发,它都会继续并引发一个LostFocus
导致绑定更新的附加事件。它像这样使用
<TextBox Text="{Binding Test}" LostKeyboardFocus="UIElement_OnLostKeyboardFocus" local:MainWindow.BindOnLostKeyboardFocus="True" />