在UserControl中将焦点设置到TextBox

5
在我的程序中,我有一个用户控件,使用内容提供器在窗口上显示数据。我想简单地在启动时设置窗口中某个textBox的光标焦点。
通常情况下,我会通过窗口的代码后台来完成这个操作,像这样:textBox.Focus(); 然而,textBox是在用户控件中定义的,并且似乎不能以同样的方式工作。到目前为止,我已经尝试了与上面相同的方法,在用户控件的代码后台中进行操作。
为什么这不起作用?如果textBox在用户控件中定义,如何设置焦点?
我已经尝试过的方法....:
用户控件:
public UserControl()
{
    InitializeComponent();

    FocusManager.SetFocusedElement(this, textBox);
}

用户控件:

public UserControl()
{
    InitializeComponent();

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

https://dev59.com/t3RA5IYBdhLWcg3wzhXZ - Trevor Elliott
3个回答

5
请尝试使用以下代码: FocusManager.SetFocusedElement
FocusManager.SetFocusedElement(parentElement, textBox)

或者从MSDN网站获得:
textBox.Focusable = true;
Keyboard.Focus(textBox);

注意:无法在构造函数中设置焦点。此时,UI元素尚未创建。您应该在控件的Loaded事件中设置焦点。

好的,我试图在用户控件的构造函数中设置焦点。 我的控件(即textBox)的加载事件在哪里? - Eric after dark
我已经在我的用户控件构造函数中尝试了这两个方法,但都没有任何效果。 - Eric after dark
2
private void Document_Loaded(object sender, RoutedEventArgs e) { textbox.Focusable = true; textbox.Focus();} - JTFRage
好的,我需要将它附加到任何XAML上,这样程序才会调用它吗?编辑:没事了,搞定了,非常感谢。 - Eric after dark

3
有点晚了,但对我真正有用的是:
public UserControl()
    {
        InitializeComponent();

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

与 https://dev59.com/-Wkw5IYBdhLWcg3w9vJ-#9624985 在其核心上相似。 - StayOnTarget

2
您可以尝试在用户控件LoadedInitialized事件中设置焦点。例如:
private void MyWpfControl_Load(object sender, EventArgs e)
{
    textBox.Focusable = true;
    Keyboard.Focus(textBox);
}

提示信息:使用Loaded事件Initialized事件


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接