[英]Command not executing in row level ContextMenu on DataGrid in WPF C#
I have my template declared like so - 我有这样声明的模板-
<DataGrid.Resources>
<ContextMenu x:Key="RowMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Remove" Command="{Binding Cancel}" />
</ContextMenu>
</DataGrid.Resources>
I'm applying the template using row style - 我正在使用行样式应用模板-
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="ContextMenu" Value="{StaticResource RowMenu}" />
</Style>
</DataGrid.RowStyle>
The menu shows up ok 菜单显示正常
But the command (on the ItemListViewModel) does not execute when a context menu item is clicked 但是单击上下文菜单项时,命令(在ItemListViewModel上)不执行
public class ItemListViewModel : INotifyPropertyChanged
{
public void Cancel()
{
MessageBox.Show("Cancel test");
}
...
}
My binding is otherwise working properly, as I can do things like this - 否则,我的绑定工作正常,因为我可以做这样的事情-
foreach (ItemListViewModel ul in mylist.SelectedItems)
MessageBox.Show(item.FullDescription);
I've been at this all night trying to figure it out. 我整夜都在努力寻找答案。 Just started with WPF today. 今天刚开始使用WPF。
Please somebody tell me where I've gone wrong 请有人告诉我我哪里出错了
I don't think you can bind to a simple method. 我认为您无法绑定到一种简单的方法。 You need to bind to a command that should be an implementation of ICommand
interface. 您需要绑定到应该是ICommand
接口实现的命令。 In you case you need to create a class that would implement that interface and add property of that class type to your model. 在这种情况下,您需要创建一个将实现该接口的类,并将该类类型的属性添加到模型中。
See this example as a reference: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx 参见以下示例作为参考: http : //msdn.microsoft.com/zh-cn/magazine/dd419663.aspx
I decided ListView was better for my needs and I'm using that instead. 我认为ListView可以更好地满足我的需求,而我正在使用它。 I'm no longer trying to bind the context menu to the item, but rather have a single context menu for the whole listview and simply enable or disable items in the ContextMenuOpen event where need be. 我不再试图将上下文菜单绑定到该项目,而是为整个listview提供了一个上下文菜单,并仅在需要的地方在ContextMenuOpen事件中启用或禁用项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.