WPF:这种行为是故意的吗? PreviewLostKeyboardFocus 和 LostKeyboardFocus

WPF: Is this behavior intended? PreviewLostKeyboardFocus and LostKeyboardFocus

我有一个文本框,我想在用户离开文本框时保存内容。我计划使用 PreviewLostKeyboardFocus,但它没有按预期工作。

<TextBox PreviewLostKeyboardFocus="textBox2_PreviewLostKeyboardFocus" 
         LostKeyboardFocus="textBox2_LostKeyboardFocus" />

当我在同一个应用程序中单击另一个控件时,我首先得到 PreviewLostKeyboardFocus 事件,然后是 LostKeyboardFocus 事件。但是当我激活另一个应用程序时,PreviewLostKeyboardFocus 事件根本不会发生。我只得到 LostKeyboardFocus。

这是预期的行为。

切换到另一个应用程序时不会引发 PreviewLostKeyboardFocus 事件。

首先处理该事件的主要目的是防止键盘焦点改变:https://msdn.microsoft.com/en-us/library/system.windows.input.keyboard.previewlostkeyboardfocus(v=vs.110).aspx

并且如果当您切换到另一个应用程序时引发该事件,您将能够通过处理该事件并设置 Handled 属性 来防止键盘焦点发生变化=12=] 到 true,这将有效地阻止用户在 运行 您的应用程序时将焦点放在屏幕上的任何其他元素。