如何在 Window 失去焦点时更新文本框的值?

How to update a TextBox's value when its Window loses focus?

一点上下文

<TextBox Text="{Binding Value, UpdateSourceTrigger=LostFocus}"/>

TextBox 控件有一个名为 UpdateSourceTrigger 的绑定选项,默认设置为 LostFocus。但是,这仅在 TextBox 在其自身 Window 中失去焦点时才有效 。我需要更新绑定,即使整个所有者 Window 失去了焦点。

可能的解决方案?

现在,Window.Deactivated 事件似乎做得很好。

<Window x:Class="MyWindow" Deactivated="OnDeactivated">

关于问题

也就是说,考虑到 TextBox 位于 UserControl 对象的几层之下,TextBox 如何监听其父 Window 的 Window.Deactivated 事件。

Window --> UserControl --> UserControl --> TextBox

如何使 向下 从 Window 到 TextBox 的事件冒泡? (即:让 TextBox 监听 Window.Deactivated 事件

或者也许有更好的解决方案?

为什么不在 window class 中为 window deactivated 事件添加一个处理程序,然后(在您的处理程序中)更新您的用户控件(给它一个 Update 方法或其他东西) ?

您可以使用自定义行为 class 来实现此功能

public class CustomBehavior : Behavior<UIElement>
{
//use the override the OnAttached()
}

WPF 4.5 现在支持延迟绑定。与 PropertyChanged 相结合,这意味着一旦用户完成输入,该值将在延迟 X 毫秒后更新。非常棒,对吧?

Text="{Binding Value, UpdateSourceTrigger=PropertyChanged, Delay=2000}"/>