Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 637
Lukas Avatar asked Dec 12 '22 02:12

Lukas


1 Answers

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;
}
like image 188
King King Avatar answered Dec 27 '22 07:12

King King