Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

context menu for removing items in listview

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?

like image 830
M.E. Avatar asked Jun 18 '12 11:06

M.E.


2 Answers

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>
like image 192
blindmeis Avatar answered Sep 18 '22 15:09

blindmeis


ContextMenus are disconnected, you cannot use ElementName bindings. One workaround would be using Binding.Source and x:Reference which requires you to extract parts that use it to be in the resources (due to cyclical dependency errors). You can just put the whole context menu there.

An example:

<ListBox Name="lb" Height="200">
    <ListBox.Resources>
        <ContextMenu x:Key="cm">
            <MenuItem Header="{Binding ActualHeight, Source={x:Reference lb}}" />
        </ContextMenu>
    </ListBox.Resources>
    <ListBox.ContextMenu>
        <StaticResource ResourceKey="cm" />
    </ListBox.ContextMenu>
</ListBox>
like image 28
H.B. Avatar answered Sep 21 '22 15:09

H.B.