How to remove all event handlers from an event

后端 未结 18 1810
再見小時候
再見小時候 2020-11-22 01:20

To create a new event handler on a control you can do this

c.Click += new EventHandler(mainFormButton_Click);

or this

c.Cli         


        
18条回答
  •  离开以前
    2020-11-22 01:36

    I found another working solution by Douglas.

    This method removes all event handlers which are set on a specific routet event on a element.
    Use it like

    Remove_RoutedEventHandlers(myImage, Image.MouseLeftButtonDownEvent);
    

    Full code:

    /// 
    /// Removes all event handlers subscribed to the specified routed event from the specified element.
    /// 
    /// The UI element on which the routed event is defined.
    /// The routed event for which to remove the event handlers.
    public static void RemoveRoutedEventHandlers(UIElement UIElement_Target, RoutedEvent RoutetEvent_ToRemove)
    {
        // Get the EventHandlersStore instance which holds event handlers for the specified element.
        // The EventHandlersStore class is declared as internal.
        PropertyInfo PropertyInfo_EventHandlersStore = typeof(UIElement).GetProperty(
            "EventHandlersStore", BindingFlags.Instance | BindingFlags.NonPublic);
        object oEventHandlersStore = PropertyInfo_EventHandlersStore.GetValue(UIElement_Target, null);
    
        // If there's no event handler subscribed, return
        if (oEventHandlersStore == null) return;
    
        // Invoke the GetRoutedEventHandlers method on the EventHandlersStore instance 
        // for getting an array of the subscribed event handlers.
        MethodInfo MethodInfo_RoutedEventHandlers = oEventHandlersStore.GetType().GetMethod(
            "GetRoutedEventHandlers", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        RoutedEventHandlerInfo[] RoutedEventHandlerInfos = (RoutedEventHandlerInfo[])MethodInfo_RoutedEventHandlers.Invoke(
            oEventHandlersStore, new object[] { RoutetEvent_ToRemove });
    
        // Iteratively remove all routed event handlers from the element.
        foreach (RoutedEventHandlerInfo RoutedEventHandlerInfo_Tmp in RoutedEventHandlerInfos)
            UIElement_Target.RemoveHandler(RoutetEvent_ToRemove, RoutedEventHandlerInfo_Tmp.Handler);
    }
    

提交回复
热议问题