简体   繁体   English

窗体中UserControl内部的焦点控件

[英]Focus control inside an UserControl in a Form

I have a Form let it's name be MyForm and there is a UserControl in the Form, let it's name be MyUserControl . 我有一个Form,将其命名为MyForm,并且在Form中有一个UserControl,将其命名为MyUserControl I'd like to set focus to a TextBox that is in MyUserControl . 我想将焦点设置在MyUserControl中的TextBox上。

So the connection looks like this: 所以连接看起来像这样:

- Form ┐
--    UserControl ┐
---            TextBox

When MyForm shown, also MyUserControl is shown and the focus DOES NOT WORK with this solution: 当显示MyForm ,也显示MyUserControl ,并且此解决方案无法使用焦点:

public partial class MyUserControl : UserControl
{

    public MyUserControl()
    {
        InitializeComponent();
    }

    private void MainFormV2HWT_Shown(object sender, EventArgs e)
    {
       ActiveControl = textBox1;
    }
}

BUT IT WORKS WITH THIS SOLUTION: 但此解决方案可以起作用:

public partial class MyUserControl : UserControl
{
    // ...

    public TextBox MyTextBox
    {
        get
        {
            return textBox1;
        }
    }

    // ...
}

public class MyForm() : Form
{
    public MyForm()
    {
        InitalizeComponents();
    }


    private void MyForm_Shown(object sender, EventArgs e)
    {
        ActiveControl = myUserControl.MyTextBox;
    }
}

I also tried to set ActiveControl to MyUserControl first, then in MyUserControl set ActiveControl to MyTextBox but it also doesn't work. 我也尝试过先将ActiveControl设置为MyUserControl ,然后在MyUserControl中将ActiveControl设置为MyTextBox但它也不起作用。

Question: 题:

Is my working solution is a nice solution or is there any easier, more nice solution, that's not using MyTextBox from MyForm ? 我的工作解决方案是一个不错的解决方案,还是有没有更简单,更不错的解决方案,而不是使用MyForm MyTextBox

Firstly, You have to focus user control in the form. 首先,您必须将用户控件集中在表单中。 Something like this: 像这样:

public class MyForm() : Form
{
    private void MyForm_Shown(object sender, EventArgs e)
    {
        myUserControl.Focus();
    }
}

and then in the user control: 然后在用户控件中:

public partial class MyUserControl : UserControl
{
    private void MyUserControl _Shown(object sender, EventArgs e)
    {
       textBox1.Select();
    }
}

This seems the only combination (Focus -> Select) which works. 这似乎是唯一有效的组合(焦点->选择)。

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

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