wpf 将焦点设置在 UserControl 中的 TextBox 上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19434087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:52:57  来源:igfitidea点击:

Set focus on TextBox in UserControl

c#wpfuser-controlstextbox

提问by Eric after dark

In my program I have a user control that displays data on a window using a content presenter. I would like to simply set the cursor focus on a certain textBoxin my window at startup.

在我的程序中,我有一个用户控件,它使用内容展示器在窗口上显示数据。我想textBox在启动时简单地将光标焦点设置在我的窗口中的某个上。

Usually I would do this through the code-behind of the window, like this: textBox.Focus();

通常我会通过窗口的代码隐藏来做到这一点,如下所示: textBox.Focus();

However, the textBoxis defined in the user control, and doesn't seem to work the same way. So far I have tried the same method as above in the user control's code-behind.

但是,textBox是在用户控件中定义的,并且工作方式似乎不同。到目前为止,我已经在用户控件的代码隐藏中尝试了与上面相同的方法。

Why doesn't this work? How do I set the focus if the textBoxis defined in a user control?

为什么这不起作用?如果textBox是在用户控件中定义的,如何设置焦点?

What I have tried....:

我尝试过的....:

User Control:

用户控制:

public UserControl()
{
    InitializeComponent();

    FocusManager.SetFocusedElement(this, textBox);
}

User Control:

用户控制:

public UserControl()
{
    InitializeComponent();

    textBox.Focusable = true;
    Keyboard.Focus(textBox);
}

回答by JTFRage

Give this a try: FocusManager.SetFocusedElement

试试这个: FocusManager.SetFocusedElement

FocusManager.SetFocusedElement(parentElement, textBox)

or from the msdn website:

或从 msdn 网站:

textBox.Focusable = true;
Keyboard.Focus(textBox);

Note: You can't set focus in a constructor. If you are, UI Elements have not been created at that point. You should set focus during the Loaded event of your control.

注意:您不能在构造函数中设置焦点。如果是,则此时尚未创建 UI 元素。您应该在控件的 Loaded 事件期间设置焦点。

回答by Loetn

You can try setting the focus in the Loadedor Initializedevent of the User control. Eg:

您可以尝试在LoadedInitialized事件中设置焦点User control。例如:

private void MyWpfControl_Load(object sender, EventArgs e)
{
    textBox.Focusable = true;
    Keyboard.Focus(textBox);
}

Info: Loaded eventor Initialized event

信息:加载事件初始化事件

回答by Ieskudero

A little bit late but what it really worked for my was

有点晚了,但真正对我有用的是

public UserControl()
    {
        InitializeComponent();

        Dispatcher.BeginInvoke(new System.Action(() => { Keyboard.Focus(TextBox); }),
                               System.Windows.Threading.DispatcherPriority.Loaded);
    }