【发布时间】:2011-06-15 13:11:50
【问题描述】:
在我的 XAML 文件中,我有一个带有上下文菜单的 DataGrid。数据源是一个 ViewModel,它有一个属性 EntityCollection(一个 ObservableCollection)作为 DataGrid 的 ItemsSource,另一个集合 ContextMenu.MenuItems 用作在 DataGrid 上创建上下文菜单的数据源。该集合的元素有一个 Command 属性,我将其绑定到菜单项的 Command 属性:
<DataGrid Name="EntityDataGrid" ItemsSource="{Binding EntityCollection}" Height="450">
<DataGrid.ContextMenu>
<ContextMenu ItemsSource="{Binding Path=ContextMenu.MenuItems}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter"
Value="{Binding ElementName=EntityDataGrid, Path=SelectedItems}" />
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
菜单项命令的操作在 ViewModel 中具有以下签名:
private void SelectedItemsAction(object parameter)
{
// Do something with "parameter"
}
现在我的问题是当我点击上下文菜单项时我到达SelectedItemsAction,但parameter 是null。我相信我的问题出在CommandParameter 属性的设置器中。如您所见,我想将此属性绑定到 DataGrid 的 SelectedItems 属性,方法是将值设置为:
<Setter Property="CommandParameter"
Value="{Binding ElementName=EntityDataGrid, Path=SelectedItems}" />
我尝试过更简单的值作为测试:
<Setter Property="CommandParameter"
Value="{Binding ElementName=EntityDataGrid, Path=Height}" />
这里的parameter 仍然是null。然后只是为了测试是否有任何参数到达我的操作方法:
<Setter Property="CommandParameter"
Value="10" />
这行得通,我的操作方法中的parameter 现在确实是10。
将CommandParameter 值绑定到EntityDataGrid 的属性我做错了什么?有可能吗?
提前感谢您的帮助!
【问题讨论】:
标签: .net wpf binding wpfdatagrid