【问题标题】:context menu for removing items in listview用于删除列表视图中的项目的上下文菜单
【发布时间】:2012-06-20 09:10:34
【问题描述】:

我有一个显示字符串值列表的 ListView。我想为列表中的每个项目添加一个上下文菜单条目以删除所选项目。我的 XAML 如下所示:

<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 值始终为空。我添加了一个额外的按钮来删除选定的项目以检查我的命令是否有效。该按钮具有完全相同的绑定和通过按钮工作删除项目。该按钮如下所示:

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

}

任何想法为什么打开上下文菜单时所选项目为空?可能是列表视图的焦点问题?

【问题讨论】:

标签: wpf listview contextmenu


【解决方案1】:

这对我有用 CommandParameter="{Binding}"

【讨论】:

    【解决方案2】:

    H.B.是对的。但你也可以使用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>
    

    【讨论】:

    • 使用了 RelativeSource - 谢谢!
    • 请注意,这不适用于多个选择(SelectedItem 不一定指向您实际按下鼠标的元素)或者如果您在右键单击时禁用选择(SelectedItem 将为空)。
    【解决方案3】:

    ContextMenus 已断开连接,您无法使用ElementName 绑定。一种解决方法是使用Binding.Source 和x:Reference,这需要您将使用它的部分提取到资源中(由于周期性依赖错误)。你可以把整个上下文菜单放在那里。

    一个例子:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      相关资源
      最近更新 更多