简体   繁体   English

将焦点放在UserControl中的TextBox上

[英]Set focus on TextBox in UserControl

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 textBox in 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 textBox is defined in the user control, and doesn't seem to work the same way. 但是, textBox是在用户控件中定义的,似乎工作方式不同。 So far I have tried the same method as above in the user control's code-behind. 到目前为止,我已经在用户控件的后台代码中尝试了与上面相同的方法。

Why doesn't this work? 为什么不起作用? How do I set the focus if the textBox is 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);
}

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. 如果是这样,则此时尚未创建UI元素。 You should set focus during the Loaded event of your control. 您应该在控件的Loaded事件期间设置焦点。

You can try setting the focus in the Loaded or Initialized event of the User control . 您可以尝试在User controlLoadedInitialized事件中设置焦点。 Eg: 例如:

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

Info: Loaded event or Initialized event 信息: 已加载事件初始化事件

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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM