繁体   English   中英

窗体中UserControl内部的焦点控件

[英]Focus control inside an UserControl in a Form

我有一个Form,将其命名为MyForm,并且在Form中有一个UserControl,将其命名为MyUserControl 我想将焦点设置在MyUserControl中的TextBox上。

所以连接看起来像这样:

- Form ┐
--    UserControl ┐
---            TextBox

当显示MyForm ,也显示MyUserControl ,并且此解决方案无法使用焦点:

public partial class MyUserControl : UserControl
{

    public MyUserControl()
    {
        InitializeComponent();
    }

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

但此解决方案可以起作用:

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

我也尝试过先将ActiveControl设置为MyUserControl ,然后在MyUserControl中将ActiveControl设置为MyTextBox但它也不起作用。

题:

我的工作解决方案是一个不错的解决方案,还是有没有更简单,更不错的解决方案,而不是使用MyForm MyTextBox

首先,您必须将用户控件集中在表单中。 像这样:

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

然后在用户控件中:

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

这似乎是唯一有效的组合(焦点->选择)。

暂无
暂无

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

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