spi*_*les 3 c# events delegates event-handling
我正在学习事件处理程序和代理.我有一个包含4个文本框和一个列表框的表单.我想让一个代表听取4个框中任意一个的文本框更改.与委托关联的方法只是一个方法,它接受更改的文本框的文本值,并将其添加为新的列表项.我的问题是如何编写委托来监听所有文本框,当我调用函数添加列表框项时,如何传入文本框对象,因为我不明确知道哪一个引发了事件?这会包含在EventArgs e中吗?
而不是使用多个事件处理程序:
this.textBo1.TextChanged += txt_TextChanged;
this.textBo2.TextChanged += txt_TextChanged;
this.textBo3.TextChanged += txt_TextChanged;
this.textBo4.TextChanged += txt_TextChanged;
Run Code Online (Sandbox Code Playgroud)
我喜欢这样的东西:
public delegate ListenToTextBoxes(object sender, EventArgs e);
Run Code Online (Sandbox Code Playgroud)
也许这是没有意义的,因为我是代表们的新手,但对我而言,我应该能够让一个代表听一般的文本框控件,然后当它引发事件时,我投出对象发送者似乎是合理的.并获取文本框文本.但是,如何创建委托,使其仅侦听文本框或其他类型的控件?
这样的事情怎么样?
// form constructor
public MyForm()
{
InitializeComponent();
this.textBo1.TextChanged += txt_TextChanged;
this.textBo2.TextChanged += txt_TextChanged;
this.textBo3.TextChanged += txt_TextChanged;
this.textBo4.TextChanged += txt_TextChanged;
}
// event handler
void txt_TextChanged(object sender, EventArgs e)
{
var textBox = (TextBox)sender;
this.myList.Add(textBox.Text);
}
Run Code Online (Sandbox Code Playgroud)
编辑:(
根据问题更新)
实际上,以前的代码可以很容易地修改为创建一个单独的委托并将其传递给所有文本框,但它不会改变太多(仍然有四个事件订阅):
public MyForm()
{
InitializeComponent();
// EventHandler is defined as:
// delegate void EventHandler(object sender, EventArgs e)
// so its signature is equal to your delegate:
// delegate void ListenToTextBoxes(object sender, EventArgs e);
// Hence, if you receive that delegate from somewhere out, you can pass it
// to TextChange events
var myDelegate = new EventHandler(txt_TextChanged);
this.textBox1.TextChanged += myDelegate;
this.textBox2.TextChanged += myDelegate;
this.textBox3.TextChanged += myDelegate;
this.textBox4.TextChanged += myDelegate;
}
Run Code Online (Sandbox Code Playgroud)
问题是你需要TextChanged
为每个TextBox
控件订阅事件,没有神奇的方法来说"将所有TextBox.TextChange事件注册到这个委托".
但是,如果您确定要注册的所有文本框都是此控件的子项,则可以使用循环,例如:
public MyForm()
{
InitializeComponent();
var myDelegate = new EventHandler(txt_TextChanged);
foreach (var ctrl in this.Controls)
{
var txtBox = ctrl as TextBox;
if (txtBox != null)
txtBox.TextChanged += myDelegate;
}
}
Run Code Online (Sandbox Code Playgroud)