【问题标题】:Focus control inside an UserControl in a Form窗体中 UserControl 内的焦点控件
【发布时间】:2018-07-27 07:30:22
【问题描述】:

我有一个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,但它也不起作用。 p>

问题:

我的工作解决方案是一个很好的解决方案,还是有任何更简单、更好的解决方案,而不是使用来自MyFormMyTextBox

【问题讨论】:

    标签: c# .net winforms user-controls


    【解决方案1】:

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

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

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

    【讨论】:

    • 在尝试了您的代码后,我发现了一个更简单的解决方案。如果我订阅我的UserControlVisibleChanged 事件,然后设置ActiveControl = textBox1,它可以工作,不需要更多代码。
    • 好!!做你想让项目工作的事情:)
    猜你喜欢
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多