[英]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.