WPF: How to open ContextMenu from all areas of a grid control

I am trying to add ContextMenu to elements in a ListBox in WPF;

<ListBox.ItemTemplate> <DataTemplate> <Border> <Grid> <Grid.ContextMenu> <ContextMenu> <MenuItem Header = "Menu item 1"/> <MenuItem Header = "Menu item 2"/> <MenuItem Header = "Menu item 3"/> </ContextMenu> </Grid.ContextMenu> ........ ........ </Grid> </Border> </DataTemplate> </ListBox.ItemTemplate> 

The problem is that ContextMenu only opens when you click on the actual grid context, I want to open the menu by clicking anywhere in the Listbox element.

Should I wrap the Grid in some other control?

+7
c # wpf xaml contextmenu
source share
2 answers

It has been several months since I did a solid WPF development (it was transferred from application development to a real team).

From memory, you want to set the ContextMenu property to Border , and then set Border.Background=Transparent . Setting the background to transparency ensures that it will participate in hit detection.

An alternative solution will ensure that the Grid element is stretched horizontally and vertically to fit the container.

...

Also pull ContextMenu as a static resource so that it will be easier to find / change in the future.

Hope this helps (and my memory doesn't let me down).

EDIT: I already answered a similar question in StackOverflow, see my answer on WPF: displaying a context menu for GridView elements . This answer is more complete as it focuses on ListItem .

+17
source share

As you already understood, thanks to Denis, you have to set some kind of background. Yes, the transparent background is also fine:

  <Grid Background="Transparent"> <Grid.ContextMenu> <ContextMenu> <MenuItem Header = "Menu item 1"/> <MenuItem Header = "Menu item 2"/> <MenuItem Header = "Menu item 3"/> </ContextMenu> </Grid.ContextMenu> ........ ........ </Grid> 

LINK: https://blogs.msdn.microsoft.com/domgreen/2008/12/08/wpf-hit-testing-with-event-bubbling/

+2
source share

All Articles