开发者

Prevent Child Inheritence of a parent's ContextMenu

According to this code:

<StackPanel>
   <StackPanel.ContextMenu>
     <ContextMenu>
        <MenuItem Header="menuitem1"/>
        <MenuItem Header="menuitem2"/>
     </ContextMenu>
   </StackPanel.ContextMenu>

   <Button Width="100" Height="100"/>
   <Button Width="100" Height="100"/>
</StackPanel>

If you right click on the Buttons then ContextMenu will appear, children will inherit their parent’s ContextMenu.

My question is how can I prevent this feature?

Edit: I need a way in xaml if it开发者_StackOverflow社区's possible.


I found this solution

<StackPanel>
   <StackPanel.ContextMenu>
     <ContextMenu>
        <MenuItem Header="menuitem1"/>
        <MenuItem Header="menuitem2"/>
     </ContextMenu>
   </StackPanel.ContextMenu>

   <Button Width="100" Height="100">
        <Button.ContextMenu>
            <ContextMenu Visibility="Hidden"/>
        </Button.ContextMenu>
   </Button>
   <Button Width="100" Height="100"/>
</StackPanel>


On the buttons in question, you need to stop a right-click mouse event propagating up to the containing StackPanel. You can do this by handling MouseDown like this:

void button_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.RightButton == MouseButtonState.Pressed)
    {
        e.Handled = true;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜