How would it be possible to remove all event handlers of the 'Click' event of a 'Button'?

后端 未结 6 627
孤街浪徒
孤街浪徒 2020-11-28 11:56

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 = GetB         


        
6条回答
  •  不知归路
    2020-11-28 12:48

    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.

    /// 
    /// 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 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);
    
        if (eventHandlersStore == null) return;
    
        // 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 });
    
        // Iteratively remove all routed event handlers from the element.
        foreach (var routedEventHandler in routedEventHandlers)
            element.RemoveHandler(routedEvent, routedEventHandler.Handler);
    }
    

提交回复
热议问题