我的 WinForm 用户控件中有一堆文本框。这些文本框中的每一个都有一些事件处理程序,例如 On_Enter - 显示带有建议的 ListBox,On_KeyUP if Keys.Code == Keys.Enter
- SelectNextControl()。当我将该控件放在表单中时,这些事件都不会触发。如何将所有这些事件暴露给包含表单?如何使 UserControl 的事件触发该 UserControl 的事件处理程序?
问问题
1949 次
1 回答
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
参数从事件处理程序访问它们。
于 2014-11-19T16:52:04.473 回答