15

我有一个显示字符串值列表的 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);  

}

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

4

3 回答 3

40

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

    <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>
于 2012-06-18T12:11:25.930 回答
4

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>
于 2012-06-18T12:00:32.113 回答
1

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

于 2016-12-15T17:02:35.300 回答