ContextMenuOpening event not firing in WPF?

ContextMenuOpening event must be handled on an ancestor of the ContextMenu not on the ContextMenu itself. If you try handling it on the ContextMenu the event only fires when you right click once ContextMenu is already open.


Its not a bug, it is working... here is the most common mistake that most people is doing with ContextMenuOpening event... consider this two different scenario to figure out the actual cause of this problem,

SCENARIO 1 (This will not work):

<ListBox Name="lb_sizes" Height="120">
<ListBox.ContextMenu>
<ContextMenu ContextMenuOpening="My_ContextMenuOpening">
<MenuItem Header="Delete"/>
<MenuItem Header="Delete All"/>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>

SCENARIO 2 (This will work):

<ListBox Name="lb_sizes" Height="120" ContextMenuOpening="My_ContextMenuOpening">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete"/>
<MenuItem Header="Delete All"/>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>

The only difference is assigning ContextMenuOpening event to proper element... in scenario 1 it is assigned (attached) to <ContextMenu> element and in scenario 2, it is assigned to <ListBox> element which is proper way to do it and should work.


It is a bug in the framework: http://connect.microsoft.com/VisualStudio/feedback/details/353112/contextmenu-opening-event-doesnt-fire-properly

A contextmenu's opening event doesn't fire on the first right click. It only fires when you do two sequential right clicks while not moving the mouse.


I believe kurrazyman has the right answer, but it took me a while to understand it. In my case I had a TreeView control with a context menu. Using myTreeView.ContextMenu.ContextMenuOpening didn't work, but using myTreeView.ContextMenuOpening did.

Tags:

C#

Wpf

Mvvm