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>

        <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>                                           
</ListView>

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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s