Listview Binding to Context Menu

I ran into an issue at work where I had to implement custom commands on a context menu on a listview.  At first I thought I could easily bind the command parameter to my selected item in the list but it was not as simple as that.

To bind to an item of a listview, you have to use RelativeSource in your binding.  Below is an example of it being used.

<ListView ItemsSource="{Binding DataItems}">     <ListView.ContextMenu>

            <MenuItem Header="Add"
                      Command="{Binding CustomAddCommand}"/>            
            <MenuItem Header="Delete"
                    Command="{Binding CustomDeleteCommand}"                       CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}"/>
        </ContextMenu>     </ListView.ContextMenu>                                           

If you would want to set a list of selected items instead of just one item use the following in your binding for the command parameter.

CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItems}"

This technique works for anything that needs a context menu.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s