ContextMenu for ListViewItem only

I have a context menu - the problem is that I need to open it only when I click on the listviewitem element. Now it will open if I click anywhere in the list or in the title.

<ListView> <ListView.ContextMenu> <ContextMenu> <MenuItem Header="More Info" Command="{Binding MoreInfo}" /> </ContextMenu> </ListView.ContextMenu> <ListView.View> <GridView> <!-- columns and stuff here --> </GridView> </ListView.View> </ListView> 

I tried to add ContextMenu as a resource and apply it as a style, but this violates the command (clicking on More Info should open a dialog box, does not work this way)

 <ListView.Resources> <ContextMenu x:Key="ItemContextMenu"> <MenuItem Header="More Info" Command="{Binding MoreInfo}" Background="WhiteSmoke" /> </ContextMenu> </ListView.Resources> <ListView.ItemContainerStyle> <Style TargetType="{x:Type ListViewItem}" > <Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}" /> </Style> </ListView.ItemContainerStyle> 

So I'm not sure how to limit the context menu to just a list and make the team work.

+6
source share
1 answer

Use a RelativeSource in the command binding in the template and it will work:

 <ListView.Resources> <ContextMenu x:Key="ItemContextMenu"> <MenuItem Header="More Info" Command="{Binding Path=DataContext.MoreInfo, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}" Background="WhiteSmoke" /> </ContextMenu> </ListView.Resources> <ListView.ItemContainerStyle> <Style TargetType="{x:Type ListViewItem}" > <Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}" /> </Style> </ListView.ItemContainerStyle> 
+15
source

Source: https://habr.com/ru/post/954273/


All Articles