【发布时间】:2013-12-18 23:46:26
【问题描述】:
我为我的数据网格定义了以下 ContextMenu:
<igDP:XamDataGrid.ContextMenu>
<ContextMenu ItemsSource="{Binding CommandViewModels}" >
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter" Value="{Binding CommandParameter}" />
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="Icon" Value="{Binding Icon}" />
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</igDP:XamDataGrid.ContextMenu>
CommandViewModel 类定义如下:
public class CommandViewModel : ICommandViewModel
{
public CommandViewModel(string name, Image icon, ICommand command, object commandParameter = null, int index = 0)
{
Name = name;
Icon = icon;
Command = command;
CommandParameter = commandParameter;
Index = index;
}
public string Name { get; set; }
public Image Icon { get; set; }
public ICommand Command { get; set; }
public object CommandParameter { get; set; }
public int Index { get; set; }
}
当我右键单击网格中的一行时,ContextMenu 的每个 MenuItem 的样式都正确。 MenuItem 的图标、标签和命令符合预期。但是,应该作为参数传递给绑定到 MenuItem.Command 的 RelayCommand 的命令参数 CommandViewModel.CommandParameter 为 null。
我相当确定可用于绑定的命令参数不为空。这是在 .NET 4.0 上运行的 WPF 应用程序。
有人经历过吗?
【问题讨论】:
-
你有多少把握,你调试过代码吗?
-
我刚刚尝试了您的确切代码,并且参数通过了...可能是您的 ICommand 实现缺少接收参数的功能吗?
-
@Tico,我分配给 CommandParameter 的值不为空。此外,如果我修改 CommandParameter 以便可以在其 getter 中放置一个断点,则框架检索到的值不为 null。
-
@emedbo,我之前在 TreeView 上也使用过相同的代码,所以它可能是 XamDataGrid 的特殊之处。
-
即使尝试以编程方式创建 MenuItems 并且传递给 RelayCommand 的 CanExecute 的命令参数仍然为空。非常有趣的问题。
标签: c# wpf mvvm binding menuitem