我想知道如何为按钮单击设置EventHandler,以便它替换此对象的所有其他处理程序。理想情况下,它会像以下一样:
button1.Click = MessageBox.Show("Run just this!"); //Yes, the '=' instead of the '+='.
这是因为button1已经有一些点击事件,我想在确定的情况下覆盖所有其他事件。
更多例子:
button1.Click += MessageBox.Show("Event #1 has been triggered!");
button1.Click += MessageBox.Show("Event #2 and #1 have been triggered!");
button1.Click = MessageBox.Show("Event #3, and only #3, has been triggered!");
答案 0 :(得分:1)
你可以试试这个......
MSDN forums有一个解决方案。以下示例代码将从Click
删除所有button1
个事件。
你可以在按钮上保留一个事件.....
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += button1_Click;
button1.Click += button1_Click2;
button2.Click += button2_Click;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello");
}
private void button1_Click2(object sender, EventArgs e)
{
MessageBox.Show("World");
}
private void button2_Click(object sender, EventArgs e)
{
RemoveClickEvent(button1);
}
private void RemoveClickEvent(Button b)
{
FieldInfo f1 = typeof(Control).GetField("EventClick",
BindingFlags.Static | BindingFlags.NonPublic);
object obj = f1.GetValue(b);
PropertyInfo pi = b.GetType().GetProperty("Events",
BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
list.RemoveHandler(obj, list[obj]);
}
}
}
答案 1 :(得分:0)
按照设计,您通常无法取消订阅其他来电者。这是因为他们不是您的关注。你可以使用反射来破解它,但几乎可以肯定它是一个非常重要的EventHandlerList。如果你是我们对控件进行分类,你可以覆盖OnClick来做到这一点,但它似乎仍然......反社会。
如果你是订阅所有这些的人,你可以简单地......不订阅你不想运行的东西。