1

我正在尝试让 RelayCommand 与使用 MVVM Light 的 CommandParameter 一起工作。该命令在我的视图模型中定义,我想将选定的 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>
4

2 回答 2

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 的 Name 和 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>
于 2013-04-24T07:55:07.910 回答
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>
于 2015-07-16T04:04:59.650 回答