context menu for removing items in listview

M.E. picture M.E. · Jun 18, 2012 · Viewed 27.6k times · Source

I have a ListView which displays a list of string values. I want to add a context menu entry for each item in the list to remove the selected item. My XAML looks like this:

<ListView x:Name="itemsListView" ItemsSource="{Binding MyItems}">
  <ListView.ContextMenu>
    <ContextMenu>
      <MenuItem Header="Remove"
                Command="{Binding RemoveItem}"
                CommandParameter="{Binding ElementName=itemsListView, Path=SelectedItem}" />
    </ContextMenu>
  </ListView.ContextMenu>
</ListView>

The problem is that the CommandParameter value is always null. I've added an additional button to remove the selected item to check if my command works. The button has exactly the same binding and removing items via the button works. The button looks like this:

<Button Content="Remove selected item"
        Command="{Binding RemoveItem}"
        CommandParameter="{Binding ElementName=itemsListView, Path=SelectedItem}"/>

The command looks like this:

private ICommand _removeItem;

public ICommand RemoveItem
{
  get { return _removeItem ?? (_removeItem = new RelayCommand(p => RemoveItemCommand((string)p))); }
}

private void RemoveItemCommand(string item)
{
  if(!string.IsNullOrEmpty(item))
    MyItems.Remove(item);  

}

Any ideas why the selected item is null when opening the context menu? Maybe a focus problem of the listview?

Answer

blindmeis picture blindmeis · Jun 18, 2012

H.B. is right. but you can also use RelativeSource Binding

    <ListView x:Name="itemsListView" ItemsSource="{Binding MyItems}">
        <ListView.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Remove"
            Command="{Binding RemoveItem}"
            CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}" />
            </ContextMenu>
        </ListView.ContextMenu>
    </ListView>