我有一个扩展UserControl
的控件。此控件包含两个ComboBox控件。我创建了一个事件处理程序,当其中一个组合发生变化时会触发:
public event EventHandler ComboChanged
{
add { cmbA.SelectedIndexChanged += value; cmbB.SelectedIndexChanged += value; }
remove {...}
}
当我向此事件添加事件处理程序时,是否有任何方法可以将sender
报告为自定义控件(即ComboBox的父控件)而不是ComboBox本身?或者我想做一些我不应该做的事情?
答案 0 :(得分:3)
你应该有这样的东西:
public event EventHandler MyControlChanged
然后在你的userControl中为每个ComboBox提供两个函数
protected void oncmbA_SelectedIndexChanged(object sender, EventArgs e)
{
if (MyControlChanged!=null)
MyControlChanged(this, e);//or some new Eventagrs that you wish to communicate
}
protected void oncmbB_SelectedIndexChanged(object sender, EventArgs e)
{
if (MyControlChanged!=null)
MyControlChanged(this, e);//or some new Eventagrs that you wish to communicate
}
然后会引用UserControl而不是引发UserControl事件的组合框。
答案 1 :(得分:3)
Yoann的答案是要走的路。这是一个类似的模式,但有一些细微的差别。
// Default listener makes null-check unnecessary when raising event.
// Note that no custom implementations are provided for add, remove.
public event EventHandler ComboChanged = delegate { };
...
foreach(var comboxBox in new[] {cmbA, cmbA})
{
// Attach listener to combo-box's event that raises our own event.
// Lambda-expression is ok since we don't intend to ever unsubscribe.
comboBox.SelectedIndexChanged += (sender, args) => ComboChanged(this, args);
}