窗体中 UserControl 内的焦点控件
Focus control inside an UserControl in a Form
我有一个表单,将其命名为 MyForm,表单中有一个 UserControl,将其命名为 MyUserControl。我想将焦点设置到 MyUserControl.
中的文本框
所以连接看起来像这样:
- 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();
}
}
这似乎是唯一有效的组合(焦点 -> Select)。
我有一个表单,将其命名为 MyForm,表单中有一个 UserControl,将其命名为 MyUserControl。我想将焦点设置到 MyUserControl.
中的文本框所以连接看起来像这样:
- 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();
}
}
这似乎是唯一有效的组合(焦点 -> Select)。