Search code examples
c#wpfcontextmenu

WPF ContextMenu disappears when clicked


I have a WPF application and I added a ContextMenu for a grid. The user makes a selection on the grid and thereafter; a ContextMenu appears. I have some textboxes on the ContextMenu where the user can enter some values but if the user clicks the ContextMenu itself (and not inside the textbox) the dialog disappears. I want to prevent this and I tried to get some event that dictate when the ContextMenu has been clicked.

private void CreateContextMenu()
{
  detectionInfoContextMenu = new ContextMenu(); //create an instance of the class     
   //selectionBoxCanvas.ContextMenu = detectionInfoContextMenu;
   playVideoGrid.ContextMenu = detectionInfoContextMenu;
   detectionInfoContextMenu.MouseDown += detectionInfoContextMenu_MouseDown;
}

void detectionInfoContextMenu_MouseDown(object sender, MouseButtonEventArgs e)
{
    if(e.LeftButton == MouseButtonState.Pressed)
    MessageBox.Show("You clicked me!");
}

I am trying to get the Mouse button events to determine if the Left mouse button was clicked. This seems to work very well on other control e.g. canvas etc but does not seem to work here on the ContextMenu. Am I using the wrong event?


Solution

  • You can use StaysOpenOnClick to prevent the closing of the menu:

    <MenuItem StaysOpenOnClick="True">Test</MenuItem>
    

    Or you use a Popup as Ivan Zub suggested in the comments.

    And here an example with a TextBox inside the menu:

    <ContextMenu>
        <MenuItem StaysOpenOnClick="True">
            <MenuItem.Header>
                <TextBox Width="100" />
            </MenuItem.Header>
        </MenuItem>
    </ContextMenu>