.net - Keyboard.Focus(item) 和 item.Focus() 有什么区别?

标签 .net wpf

在 WPF 中,有两种方法可以将焦点设置到元素上。
您可以调用 input 元素的 .Focus() 方法,也可以使用 input 元素作为参数调用 Keyboard.Focus() 。

// first way:
item.Focus();
// alternate way:
Keyboard.Focus(item);

这两者有什么区别?在某些情况下,是否有特殊原因需要使用其中一种而不是另一种?
到目前为止,我没有注意到任何区别 - 无论我使用什么方法,该项目总是获得逻辑焦点以及键盘焦点。

最佳答案

item.Focus()的第一件事情之一是打电话Keyboard.Focus( this ) .如果失败,则调用 FocusManager ,正如 decasteljau 所回答的那样。

以下内容是从 Reflector 中的反编译器 View 中复制的.

这是来自 UIElement ( UIElement3D 是一样的):

public bool Focus()
{
    if (Keyboard.Focus(this) == this)
    {
        return true;
    }
    if (this.Focusable && this.IsEnabled)
    {
        DependencyObject focusScope = FocusManager.GetFocusScope(this);
        if (FocusManager.GetFocusedElement(focusScope) == null)
        {
            FocusManager.SetFocusedElement(focusScope, this);
        }
    }
    return false;
}

这是来自 ContentElement :
public bool Focus()
{
    return (Keyboard.Focus(this) == this);
}

关于.net - Keyboard.Focus(item) 和 item.Focus() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/197088/

相关文章:

c# - 为什么 Dispose() 应该处理托管资源而不是终结器?

c# - WPF 窗口显示空白

c# - WPF 启动画面和主窗口加载事件

wpf - 如何阻止 Main 在 WPF 中自动生成?

c# - 为什么任何长度的 key 都适用于 RijndaelManaged?

c# - 哪些结构使用 .NET 4 中的 ThreadPool?

.net - 编译时引用.NET dll(单声道)

.NET ListView 列顺序问题

wpf - 在 XAML 中创建嵌套类的实例

wpf - Style.Trigger 上的自定义 DependencyProperty