所以,如果我理解正确,我认为有两种方法可以继续:
方法 1
在 UserControl 中,将每个文本框(或您感兴趣的文本框)的 Modifiers 属性设置为 public:
然后在使用此 UserControl 的表单中,您可以访问所有这些文本框以及它们的事件:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
myUserControl1.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
}
}
方法 2
(取自this post)
您可以为您的 UserControl 创建新事件,只需将底层文本框的事件传递出去。然后,底层文本框可以对 UserControl 保持私有。
在 UserControl 中添加这个事件:
public event KeyEventHandler TextBox1KeyDown
{
add { textBox1.KeyDown += value; }
remove { textBox1.KeyDown -= value; }
}
或者您可以创建一个处理所有文本框的事件:
public event KeyEventHandler AnyTextBoxKeyDown
{
add
{
textBox1.KeyDown += value;
textBox2.KeyDown += value;
textBox3.KeyDown += value;
...
}
remove
{
textBox1.KeyDown -= value;
textBox2.KeyDown -= value;
textBox3.KeyDown -= value;
...
}
}
现在您的 UserControl 有自己的事件,表单中的代码可以使用:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
myUserControl1.TextBox1KeyDown += new KeyEventHandler(myUserControl1_TextBox1KeyDown);
myUserControl1.AnyTextBoxKeyDown += new KeyEventHandler(myUserControl1_AnyTextBoxKeyDown );
}
private void myUserControl1_TextBox1KeyDown(object sender, KeyEventArgs e)
{
/* We already know that TextBox1 was pressed but if
* we want access to it then we can use the sender
* object: */
TextBox textBox1 = (TextBox)sender;
/* Add code here for handling when a key is pressed
* in TextBox1 (inside the user control). */
}
private void myUserControl1_AnyTextBoxKeyDown(object sender, KeyEventArgs e)
{
/* This event handler may be triggered by different
* textboxes. To get the actual textbox that caused
* this event use the following: */
TextBox textBox = (TextBox)sender;
/* Add code here for handling when a key is pressed
* in the user control. */
}
}
请注意,虽然这种方法在 UserControl 中保持文本框私有,但仍可以通过 sender 参数从事件处理程序访问它们。