Home > DeveloperSection > Forums > ContextMenu for ListViewItem only
marcel ethan
marcel ethan

Total Post:105

Points:735
Posted on    September-23-2013 5:15 AM

 WPF
Ratings:


 1 Reply(s)
 2632  View(s)
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.



Sumit Kesarwani

Total Post:378

Points:2694
Posted on    September-23-2013 7:03 AM

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>


Don't want to miss updates? Please click the below button!

Follow MindStick