开发者

Prevent Child Inheritence of a parent's ContextMenu

开发者 https://www.devze.com 2023-03-12 21:23 出处:网络
According to this code: <StackPanel> <StackPanel.ContextMenu> <ContextMenu> <MenuItem Header=\"menuitem1\"/>

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

精彩评论

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