context menu for removing items in listview

戏子无情 提交于 2019-12-31 13:14:15

问题


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?


回答1:


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>



回答2:


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>



回答3:


This work for me CommandParameter="{Binding}"



来源:https://stackoverflow.com/questions/11082162/context-menu-for-removing-items-in-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!