上下文菜单,用于删除列表视图中的项目 [英] context menu for removing items in listview

查看:66
本文介绍了上下文菜单,用于删除列表视图中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ListView,它显示字符串值列表.我想为列表中的每个项目添加一个上下文菜单项,以删除所选的项目.我的XAML看起来像这样:

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>

问题在于CommandParameter值始终为null.我添加了一个附加按钮来删除所选项目,以检查我的命令是否有效.该按钮具有完全相同的绑定,并且通过该按钮删除项目是可行的.该按钮如下所示:

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}"/>

命令如下:

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);  

}

有什么想法为什么打开上下文菜单时所选项目为空?也许是listview的焦点问题?

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

推荐答案

HB是对的.但您也可以使用RelativeSource绑定

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>

这篇关于上下文菜单,用于删除列表视图中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆