Sunday, 22 November 2009

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.

No comments: