如何删除所有Click事件处理程序?
可能重复: 如何删除Button的Click事件的所有事件处理程序?
我想从按钮中删除所有单击事件处理程序。 我在Stack Overflow问题中找到了这个方法如何从控件中删除所有事件处理程序 。
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]); }
但是这一行总是返回null:
typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
这种方法写于2006年。
这个方法有最新版本吗?
注意:我正在使用WPF和.NET 4.0。
以下是一个有用的实用程序方法,用于检索任何路由事件的所有订阅事件处理程序:
/// /// Gets the list of routed event handlers subscribed to the specified routed event. /// /// The UI element on which the event is defined. /// The routed event for which to retrieve the event handlers. /// The list of subscribed routed event handlers. public static RoutedEventHandlerInfo[] GetRoutedEventHandlers(UIElement element, RoutedEvent routedEvent) { // Get the EventHandlersStore instance which holds event handlers for the specified element. // The EventHandlersStore class is declared as internal. var eventHandlersStoreProperty = typeof(UIElement).GetProperty( "EventHandlersStore", BindingFlags.Instance | BindingFlags.NonPublic); object eventHandlersStore = eventHandlersStoreProperty.GetValue(element, null); // Invoke the GetRoutedEventHandlers method on the EventHandlersStore instance // for getting an array of the subscribed event handlers. var getRoutedEventHandlers = eventHandlersStore.GetType().GetMethod( "GetRoutedEventHandlers", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var routedEventHandlers = (RoutedEventHandlerInfo[])getRoutedEventHandlers.Invoke( eventHandlersStore, new object[] { routedEvent }); return routedEventHandlers; }
使用上面的方法,您的方法的实现变得非常简单:
上述就是C#学习教程:如何删除所有Click事件处理程序?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
private void RemoveClickEvent(Button b) { var routedEventHandlers = GetRoutedEventHandlers(b, ButtonBase.ClickEvent); foreach (var routedEventHandler in routedEventHandlers) b.Click -= (RoutedEventHandler)routedEventHandler.Handler; }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1022463.html