WPF MVVM ContextMenu 绑定到 ObservableCollection命令未触发
我正在尝试使用 MVVM 将 ObservableCollection 绑定到 ContextMenu。但是当我尝试触发命令时什么也没有发生。另外,我需要将字符串作为命令参数传递给事件。
下面是xaml代码:
<ContextMenu Name="ctxAddApplication" ItemsSource="{Binding Path=ApplicationTypes}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Command" Value="{Binding AddRequirementCommand}"/>
<Setter Property="CommandParameter" Value="{Binding}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
下面是视图模型代码:
public ObservableCollection<string> ApplicationTypes { get; private set; }
public ComposableCommand AddRequirementCommand { get; private set; }
this.AddRequirementCommand = new ComposableCommand(this.AddRequirementView);
private void AddRequirementView(object applicationName) {}
请帮助!!!
I am trying to bind an ObservableCollection to a ContextMenu using MVVM. But when i try to fire the command nothing is happening. also, i need to pass the string as command parameter to the event.
Below is the xaml code:
<ContextMenu Name="ctxAddApplication" ItemsSource="{Binding Path=ApplicationTypes}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Command" Value="{Binding AddRequirementCommand}"/>
<Setter Property="CommandParameter" Value="{Binding}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
Below is the View Model Code:
public ObservableCollection<string> ApplicationTypes { get; private set; }
public ComposableCommand AddRequirementCommand { get; private set; }
this.AddRequirementCommand = new ComposableCommand(this.AddRequirementView);
private void AddRequirementView(object applicationName) {}
Please help !!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以防万一您需要代码:
Just in case you need the code:
每个菜单项的数据上下文将是它所绑定的任何内容。在您的例子中,是一个字符串,因为您的
ApplicationTypes
属性是字符串的集合。因此,用于设置命令的绑定将不起作用,因为String
类型上没有AddRequirementCommand
属性。The data context for each menu item will be whatever it is bound to. In your case, a string because your
ApplicationTypes
property is a collection of strings. Thus, your binding to set the command won't work because there is noAddRequirementCommand
property on typeString
.每个项目的 ContextMenu 视图内部都绑定到集合中的项目。
这将尝试在字符串类中找到“AddRequirementCommand”。在此绑定中使用RelativeSource。还可以使用 VS 调试器和输出窗口来查看绑定错误,这通常很有帮助。
Inside ContextMenu view for each item is bound to the item from the collection.
this will try to locate 'AddRequirementCommand' in string class. Use RelativeSource in this Binding. Also use VS debugger and Output window to see binding errors, it helps a lot usually.