locked
how to remove event handlers by style? RRS feed

  • Question

  • hi.

    i want to remove this event handler:

    <Style TargetType="ContextMenu" x:Key="treeItemContextMenuStyle" >
                <EventSetter Event="ContextMenu.Loaded"  Handler="mainContextMenu_Loaded"/>
            </Style>

    private void mainContextMenu_Loaded(object sender, EventArgs e)
            {
                ContextMenu mainContextMenu = (ContextMenu)sender;
    
                mainContextMenu.Loaded -= mainContextMenu_Loaded;
                //this code not work for remove event handler
            }
    Tuesday, July 16, 2013 4:58 AM

Answers

  • Hi Ali Visual Studio,

    According to your code and description, I got that you want to find  a way to remove event handlers which were defined in a style.

    Here are some reference about EventSetter and its HandledEventsToo Property:

    #EventSetter Class
    http://msdn.microsoft.com/en-us/library/system.windows.eventsetter.aspx

    #EventSetter.HandledEventsToo Property
    http://msdn.microsoft.com/en-us/library/system.windows.eventsetter.handledeventstoo.aspx

    From reading up on above sections, you'll have to have a dummy event which sets e.Handled. EventSetter states, "Handlers attached through event setters are invoked after any class handlers for an event, and also after any instance handlers. As a result, if a class handler or instance handler marks an event handled in its arguments, then the handler declared by an event setter is not invoked, unless the event setter specifically sets HandledEventsToo true."

    So you can remove your event handler by doing this:

    In XAML:

    <Style TargetType="ContextMenu" x:Key="treeItemContextMenuStyle" >
                <EventSetter Event="ContextMenu.Loaded"  Handler="mainContextMenu_Loaded"/>
    </Style>

    Code behind:

    private void mainContextMenu_Loaded(object sender, EventArgs e)
    {
                ContextMenu mainContextMenu = (ContextMenu)sender;
    
                //remove event handler
                e.Handled = true;            
    }

    Here are some references about your problem:

    #Removing event handlers in xaml style?
    http://stackoverflow.com/questions/1239083/removing-event-handlers-in-xaml-style


    • Edited by IssueKiller Tuesday, July 16, 2013 9:46 AM adjust
    • Marked as answer by Lisa Zhu Saturday, July 27, 2013 7:23 AM
    Tuesday, July 16, 2013 9:41 AM