GotFocus
和 GotKeyboardFocus
以及类似的 LostFocus
和 LostKeyboardFocus
之间有什么区别?
很抱歉这个简单的问题,但是,我用谷歌搜索并阅读了很多博客文章,但我仍然感到困惑。似乎没有人知道到底有什么区别:
更新:
我的用法:
我正在通过扩展 Control
类来创建自定义控件。类似于 ComboBox
但具有其他一些效果。我试图通过设置属性来打开和关闭 Popup
:IsDropDownOpen
就像通过 GotFocus
的 ComboBox
> 和 LostFocus
事件。我不希望 Popup
在我 Alt+Tab
编辑窗口时关闭,但在我单击 Button
时关闭例如,或者我转到 TextBox
。我做了:
private static void OnGotFocusHandler(object sender, RoutedEventArgs e) {
if (e.Handled)
return;
((SearchBox)sender).IsDropDownOpen = true;
e.Handled = true;
}
private static void OnLostFocusHandler(object sender, RoutedEventArgs e) {
if (e.Handled)
return;
((SearchBox)sender).IsDropDownOpen = false;
e.Handled = true;
}
GotFocus
有效。但是 Lost
没有。如果我在 LostKeyboardFocus
中执行 Lost
操作,那么当我 Alt+Tab
时,窗口或 Window
将变为非事件状态,然后调用该方法,而我不想。我该如何解决?
最佳答案
MSDN对焦点进行了概述,但我将在此处尝试对其进行解释。
WPF 有两个关于焦点的概念。有物理键盘焦点,也有逻辑焦点。只有一个元素可以有键盘焦点(如果应用程序不是事件应用程序,则没有元素会有键盘焦点)。
多个项目可以有逻辑焦点。事实上,您可以创建新的“焦点范围”。根据 MSDN:
When keyboard focus leaves a focus scope, the focused element will lose keyboard focus but will retain logical focus. When keyboard focus returns to the focus scope, the focused element will obtain keyboard focus. This allows for keyboard focus to be changed between multiple focus scopes but ensures that the focused element in the focus scope regains keyboard focus when focus returns to the focus scope.
您可以通过设置 Panel
在元素(通常是 FocusManager.IsFocusScope="True"
)上定义自己的焦点范围.默认情况下作为焦点范围的 WPF 中的控件是 Window
, MenuItem
, ToolBar
, 和 ContextMenu
.
如果您考虑使用多个 Window
,这是有道理的在您的应用程序中。当你Alt-Tab
在它们之间,您希望键盘焦点返回到上次 Window
时的相同位置有重点。通过将键盘焦点和逻辑焦点分开,您可以实现这一点。
关于c# - GotFocus 和 GotKeyboardFocus 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18152056/