可以使用以下事件,但必须为每个元素附加它们:
GotKeyboardFocus,LostKeyboardFocus
.NET WPF中是否有一种方法可以全局检测焦点元素是否发生了变化?无需为所有可能的元素添加事件侦听器?
Vac*_*ano 15
您可以在任何类中执行此操作:
//In the constructor
EventManager.RegisterClassHandler(
typeof(UIElement),
Keyboard.PreviewGotKeyboardFocusEvent,
(KeyboardFocusChangedEventHandler)OnPreviewGotKeyboardFocus);
Run Code Online (Sandbox Code Playgroud)
...
private void OnPreviewGotKeyboardFocus(object sender,
KeyboardFocusChangedEventArgs e)
{
// Your code here
}
Run Code Online (Sandbox Code Playgroud)
您可以将路由事件处理程序添加到主窗口,并指定您对处理事件感兴趣.
mainWindow.AddHandler(
UIElement.GotKeyboardFocusEvent,
OnElementGotKeyboardFocus,
true
);
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以挂钩隧道预览事件:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="350" Width="525"
PreviewGotKeyboardFocus="Window_PreviewGotKeyboardFocus"
PreviewLostKeyboardFocus="Window_PreviewLostKeyboardFocus">
....
Run Code Online (Sandbox Code Playgroud)
这样,如上所示,当任何后代获得或失去键盘焦点时,窗口将在所有后代之前得到通知。
阅读本文了解更多信息。