简体   繁体   中英

Contextmenu - disable right click to open it

I have such xaml code:

<Grid x:Name="boardGrid">
    <Grid.ContextMenu>
        <ContextMenu Opacity="0.7" x:Name="menuContext">

        </ContextMenu>
    </Grid.ContextMenu>
</Grid>

I generate grid's items in code behind. What I want is to disable context menu opening on right click. I want to open it when certains conditions occur.

This is what I have in .cs file:

  • generating Unit's objects and putting them into Grid;

each object has unit.MouseRightButtonUp += unit_MouseRightButton

void unit_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    if (CurrentGame.CurrentPlayer.HasTurn == false) return; 
    .....
    ContextMenu.IsOpen = true;

}

So it means that Contextmenu should be open only if condition is fulfilled but it opens anyway.

You can set the attached property ContextMenuService.IsEnabled to false . Then you can manually popup the ContextMenu.

You must set that property for the GUI element that owns the menu. Setting it for the menu itself will do nothing.

<Grid x:Name="boardGrid" ContextMenuService.IsEnabled="false">
    <!-- ... -->
</Grid>
void unit_MouseRightButtonUp(object sender, MouseButtonEventArgs e) {
    if (CurrentGame.CurrentPlayer.HasTurn == false) return; 
    .....
    boardGrid.ContextMenu.IsOpen = true;
}

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