如何删除“Click”的所有事件处理程序? “按钮”事件?
I have a button control, and I'd need to remove all the event handlers attached to its Click event.
How would that be possible?
Button button = GetButton();
button.Click.RemoveAllEventHandlers();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
下面是一个有用的实用方法,用于删除订阅给定元素上的路由事件的所有事件处理程序。如果您愿意,您可以轻松地将其转换为扩展方法。
然后,您可以轻松地为按钮的
Click
事件调用此实用程序方法:编辑:我已复制 corona 实现的错误修复,该修复可阻止该方法在没有订阅事件处理程序时抛出
NullReferenceException
。他们的回答应该得到赞扬(和支持)。The below is a helpful utility method for removing all event handlers subscribed to a routed event on a given element. You can trivially convert this to an extension method if you like.
You could then easily call this utility method for your button's
Click
event:Edit: I've copied the bug fix implemented by corona, which stops the method from throwing a
NullReferenceException
when no event handlers are subscribed. Credit (and upvotes) should go to their answer.只是想稍微扩展道格拉斯的日常,我非常喜欢。
我发现我需要向 eventHandlersStore 添加额外的 null 检查,以处理传递的元素尚未附加任何事件的任何情况。
Just wanted to expand on Douglas' routine slightly, which I liked very much.
I found I needed to add the extra null check to eventHandlersStore to handle any cases where the element passed didn't have any events attached yet.
基本上你不能——至少在没有反思和大量肮脏的情况下不能。
事件严格来说是“订阅、取消订阅”——您无法取消订阅其他人的处理程序,就像您无法更改其他人对对象的引用一样。
You can't, basically - at least not without reflection and a lot of grubbiness.
Events are strictly "subscribe, unsubscribe" - you can't unsubscribe someone else's handler, any more than you can change someone else's reference to an object.
我在 StackOverflow 上找到了这个答案:
如何删除所有事件处理程序 控件
来自原始发布者发现的 此处:
I found this answer here on StackOverflow:
How to remove all event handlers from a control
Which the origional poster found here:
我在 Jamie Dixon 发布的代码中遇到了空错误问题,以考虑没有 Click 事件。
然后做一个小的改变,它应该适用于任何事件。
我想这可以做得更好,但它适合我当前的需求。希望这对某人有用。
I had the null error issue with the code Jamie Dixon posted to take in to account not having a Click event.
Then a small change and it should be for any event.
I imagine this could be made better but it works for my current need. Hope this is useful for someone.
我正在开发 WinForms 项目,我必须从 ToolStripMenuItem 中删除 click-EventHandler 并将其替换为我自己的处理程序。 (我必须修改单击 contextMenu 项时所采取的操作)
对我来说,来自 user2113340 的代码不起作用。我必须像这样修改它才能与 ToolStripMenuItem 一起使用:
I was working on WinForms project where I had to remove the click-EventHandler from a ToolStripMenuItem and replace it with my own Handler. (I had to modify the action taken when a contextMenu Item was clicked)
for me the code from user2113340 did not work. I had to modify it like this to work with ToolStripMenuItem: