公开UserControl的所有事件处理程序

我在WinForm UserControl中有一堆TextBoxes。 这些文本框中的每一个都有很少的事件处理程序,如On_Enter – 显示带有建议的ListBox,On_KeyUP – if Keys.Code == Keys.Enter – SelectNextControl()。 当我将该控件放在表单中时,这些事件都不会触发。 如何将所有这些事件公开给包含的表单? 如何使UserControl的事件启动该UserControl的事件处理程序?

所以,如果我理解正确,我认为有两种方法可以继续:

方法1

在UserControl中,将每个文本框(或您感兴趣的文本框)的Modifiers属性设置为public:

在此处输入图像描述

然后在使用此UserControl的表单中,您可以访问所有这些文本框,从而访问它们的事件:

 public partial class Form1 : Form { public Form1() { InitializeComponent(); myUserControl1.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown); } } 

方法2 (摘自本文 )

您可以为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参数从事件处理程序访问它们。