M.E*_*.E. 12 wpf listview contextmenu
我有一个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>
Run Code Online (Sandbox Code Playgroud)
问题是该CommandParameter值始终为null.我添加了一个额外的按钮来删除所选项目以检查我的命令是否有效.该按钮具有完全相同的绑定,并通过按钮删除项目工作.按钮看起来像这样:
<Button Content="Remove selected item"
Command="{Binding RemoveItem}"
CommandParameter="{Binding ElementName=itemsListView, Path=SelectedItem}"/>
Run Code Online (Sandbox Code Playgroud)
该命令如下所示:
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);
}
Run Code Online (Sandbox Code Playgroud)
打开上下文菜单时所选项目为空的任何想法?也许是listview的焦点问题?
bli*_*eis 33
HB是对的.但您也可以使用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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24505 次 |
| 最近记录: |