Passing ListView.SelectedItems as a ContextMenu CommandParameter

I spent quite a while trying all of what I thought were the obvious methods of doing this and couldn’t get anything to work.  Then I stumbled on a Blog by Richard Griffin at http://consultingblogs.emc.com/richardgriffin/archive/2007/02/23/WPF-Commands-a-scenic-tour-part-I.aspx that pointed me in the right direction.

	<ContextMenu>
	  <MenuItem Header="Schema"
	    Command="{Binding ExportSchemaCommand}"
	    CommandParameter="{Binding Path=PlacementTarget.SelectedItems, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />
	</ContextMenu>

Rather than trying to do something obvious like use RelativeSource or ElementName to find the BindingPath use the ContextMenu.PlacementTarget.

ListView.SelectedItems is of type System.Windows.Controls.SelectedItemCollection which is marked as Internal so in your command you have to cast it as its base class which is System.Collections.ObjectModel.ObservableCollection<object>.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>