c# - GotFocus 和 GotKeyboardFocus 的区别

标签 c# wpf c#-4.0 wpf-controls wpf-4.0

GotFocusGotKeyboardFocus 以及类似的 LostFocusLostKeyboardFocus 之间有什么区别?

很抱歉这个简单的问题,但是,我用谷歌搜索并阅读了很多博客文章,但我仍然感到困惑。似乎没有人知道到底有什么区别:

更新:

我的用法:

我正在通过扩展 Control 类来创建自定义控件。类似于 ComboBox 但具有其他一些效果。我试图通过设置属性来打开和关闭 Popup:IsDropDownOpen 就像通过 GotFocusComboBox > 和 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/

相关文章:

c# - 如何从 Windows 文本文件中拆分行(/r/n 分隔)

c# - 对具有相同长度的大量字符串进行排序

wpf - ComboBox SelectedItem 绑定(bind)将 NULL 写入源属性

wpf - 需要将“SQL SERVER 2008 R2安装”窗口置于WIX Bootstrapper捆绑软件安装窗口的前面(静默安装)

c# - 检测父任务取消的正确方法是什么?

c# - 新的 C# 异步功能是否在编译器中严格实现

c# - 添加迁移 : A parameter cannot be found that matches parameter name 'Context'

Wpf ItemsControl.ItemsPanelTemplate 作为 Grid 并在不同列中添加新项目

c# - 从 NHibernate 获取 {"could not execute batch command.[SQL: SQL not available]"} 错误

c# - 主窗体上的状态消息