ContextMenu for ListViewItem only

Total Post:104

Points:728
WPF
 3861  View(s)
Ratings:
Rate this:

I have a context menu - problem is I need it to only open when a listviewitem is clicked. Right now it will open if I click anywhere in the listview or in the header.

<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 have tried adding the ContextMenu as a resource and applying it as a style, but this breaks the command (clicking on More Info should open a dialog window, doesnt 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 not sure how to restrict the context menu to only the listviewitem and have the command work.

  1. Post:378

    Points:2694
    Re: ContextMenu for ListViewItem only

    Hi Marcel,

    Use the 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>

      Modified On Mar-31-2018 01:33:40 AM

Answer