ContextMenu通过自己的ContextMenu在子控件上

ContextMenu通过自己的ContextMenu在子控件上

本文介绍了父控件的WPF ContextMenu通过自己的ContextMenu在子控件上打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在基于Canvas的WPF中制作了一个非常漂亮的NodeGraph,当时我要通过右键单击菜单添加漂亮的功能。

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.

这些菜单是上下文相关。意味着右键单击图形的背景将显示图形ContextMenu,而右键单击图形中的节点将显示节点ContextMenu,或者如果该节点具有任何带有菜单的子控件,则这些控件。

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?

推荐答案

旧的,但以防万一有人落在这里,我可以通过以下方式解决此问题:使用以下技巧。 (在我的案例中,父控件是 Grid ,子控件是 Path ,两者都有各自的上下文菜单):

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。不要将 ContextMenu 分配给父控件。而是将其作为资源添加到其资源部分。

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

ii。处理父级的 MouseRightButtonDown 事件,并将以下代码放入其处理程序:

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。将 ContextMenu 直接分配给您的子控件。

iii. Assign ContextMenu directly to your child control.

这篇关于父控件的WPF ContextMenu通过自己的ContextMenu在子控件上打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 18:44