我正在尝试使用使用MVVM Light的CommandParameter来使用RelayCommand。该命令在我的viewmodel中定义,我想传递选定的ListBox项作为参数。该命令是绑定的,但参数不是。这可能吗?
<UserControl x:Class="Nuggets.Metro.Views.EmployeeListView"
...
DataContext="{Binding EmployeeList,Source={StaticResource Locator}}">
<ListBox x:Name="lstEmployee" ItemsSource="{Binding EmployeeItems}" Style="{StaticResource EmployeeList}" Tag="{Binding EmployeeItems}">
<ListBox.ContextMenu>
<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Edit item" Command="{Binding EditEmployeeCommand}" CommandParameter="{Binding PlacementTarget.SelectedItem,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/>
<MenuItem Header="Delete item" Command="{Binding DeleteEmployeeCommand}" CommandParameter="{Binding PlacementTarget.SelectedItem,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/>
</ContextMenu>
</ListBox.ContextMenu>
答案 0 :(得分:0)
这应该有效
<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Edit item"
Command="{Binding EditEmployeeCommand}"
CommandParameter="{Binding SelectedItem,ElementName=lstEmployee}"/>
<MenuItem Header="Delete item"
Command="{Binding DeleteEmployeeCommand}"
CommandParameter="{Binding SelectedItem,ElementName=lstEmployee}"/>
</ContextMenu>
在CommandParameter的绑定中使用ListBox als ElementName的名称,并将路径设置为SelectedItem。
<强>更新强>
上面的代码不适用于ListBox和ContextMenu,因为它们属于不同的可视树。结果是
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=lstEmployee'. BindingExpression:Path=SelectedItem; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'CommandParameter' (type 'Object')
以下XAML完成了这项工作。使用ContextMenu的PlacementTarget(即ListBox)。
<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Edit item"
Command="{Binding EditEmployeeCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}"/>
<MenuItem Header="Delete item"
Command="{Binding DeleteEmployeeCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}"/>
</ContextMenu>
答案 1 :(得分:0)
这适用于带有MVVM的TreeView或ListView。 ContextMenu中的PlacementTarget是(这里)Listview
<ListView.ContextMenu>
<ContextMenu>
<MenuItem x:Name="OpenExplorer"Header="ShowFolder"
Command="{Binding ShowExplorer}"
CommandParameter ="{Binding Path=PlacementTarget.SelectedItem,
RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
</ContextMenu>
</ListView.ContextMenu>