我有一组控件,它们在foreach循环中注册了一个CommandEventhandler:
foreach (Control control in myObject.Controls)
{
control.Command += new CommandEventHandler(myEventHandler);
}
集合中的某些控件不应该注册处理程序。
有没有办法阻止Button注册CommandEventHandler?
答案 0 :(得分:1)
如果您可以访问定义事件的代码,则可以检查“add”访问器,该访问器将决定是否添加处理程序。它看起来像下面这样:
private EventHandler _myEvent;
public event EventHandler MyEvent
{
[MethodImpl(MethodImplOptions.Synchronized)]
add
{
if (CanAddEventHandler()) // <- that's yours to implement
{
_myEvent = (EventHandler)Delegate.Combine(_myEvent, value);
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
remove
{
_myEvent = (EventHandler)Delegate.Remove(_myEvent, value);
}
}