简体   繁体   中英

WPF ContextMenu of parent control opens on child control with own ContextMenu

I made a pretty nice NodeGraph in WPF based on Canvas and am at the point where I'm adding nifty features through right-click menus.

These menus are context sensitive. Meaning a right-click on the background of the graph will display the graphs ContextMenu, whereas right-clicking a Node in the graph will display the nodes ContextMenu, or if the node has any child-controls with menus, those.

I have been postponing this particular issue for a while now but can no longer ignore it. As stated in the title: When I right-click a node, the context-menu of the graph will show. If I disable the context-menu of the graph, the nodes one shows up just fine.

This makes me believe this is an issue of the parent control taking precedence in opening a context menu. I have already tried overriding mouse events in both the parent and child controls and setting them to handled, but I just can't figure it out!

Could anyone assist me in getting rid of this very annoying issue?

Old but just in case someone lands here, I was able to solve this problem by using the following trick. (Parent control in my case is a Grid and child control is a Path , both of which have their own context menu):

i. Do not assign ContextMenu to parent control. Instead add it as a resource into its Resources section.

ii. Handle parent's MouseRightButtonDown event and put the following code in its handler:

if (!(e.OriginalSource is Path)) //Or whatever is the type of child control
{
  var cmnu = this.FindResource("ParentContextMenu") as ContextMenu;
  cmnu.IsOpen = true;
}

iii. Assign ContextMenu directly to your child control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM