简体   繁体   English

WPF中DiagramSurface上的Selected项的上下文菜单

[英]context menu for Selected item on a DiagramSurface in WPF

I have a UI which is a diagramSurface object. 我有一个UI,它是一个diagramSurface对象。 While running the application i drag and drop a element(kind of a label) on top of it. 在运行该应用程序时,我将一个元素(一种标签)拖放到其顶部。 I want to implement a CONTEXTMENU for this object. 我想为此对象实现一个CONTEXTMENU。

I have Done this 我做完了

<DiagramSurface>
     <DiagramSurface.ContextMenu>
         <ContextMenu >
                <MenuItem Header="Save" Click="MenuItem_Click"/>
         </ContextMenu>
     <DiagramSurface.ContextMenu>
</DiagramSurface>

By doing this , i am able to see the contextMenu if i click on surface where the object is not present. 这样,如果我单击不存在对象的表面,就可以看到contextMenu。 How to avoid this? 如何避免这种情况? I want to show the context menu only on the rightclick of the element. 我只想在元素的右键单击上显示上下文菜单。

As @Viv says (although I'm not sure why he didn't say it in an answer), the ContextMenu will appear when you right click anywhere on the control that you add it to. 作为@Viv说(虽然我不知道他为什么不说出来的答案),该ContextMenu会出现,当你右键点击你将它添加到控制的任何地方 Therefore, if you add it to the DiagramSurface , it will appear when you click anywhere on that control. 因此,如果将其添加到DiagramSurface ,则在该控件上的任意位置单击时将显示它。 To fix your problem, remove the declaration from the DiagramSurface control. 若要解决您的问题,请从DiagramSurface控件中删除声明。

Now, you need to add it to the control(s) that you drag and drop. 现在,您需要将其添加到拖放的控件中。 You can do as @Viv says and define your ContextMenu in the Resources section: 您可以按照@Viv的说明进行操作,并在Resources部分中定义ContextMenu

<Application.Resources>
    <ContextMenu x:Key="ContextMenu">
        <MenuItem Header="Save" Click="MenuItem_Click"/>
    </ContextMenu>
</Application.Resources>

Then set it as the ContextMenu of the drag drop element from code: 然后将其设置为代码中拖放元素的ContextMenu

ContextMenu menu = (ContextMenu)Application.Current.FindResource("ContextMenu");
element.ContextMenu = contextMenu;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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