我想绑定一个上下文菜单到一个命令列表.
- <Grid.ContextMenu>
- <ContextMenu ItemsSource="{Binding ItemContextCommands,Converter={StaticResource commandToStringConverter}}">
- <ContextMenu.ItemTemplate >
- <DataTemplate DataType="MenuItem">
- <MenuItem Command="{Binding}"></MenuItem>
- </DataTemplate>
- </ContextMenu.ItemTemplate>
- </ContextMenu>
- </Grid.ContextMenu>
commandToStringConverter只需将命令列表转换为列表中每个命令上调用ToString()的字符串列表.
如何实现每个MenuItem中的Command被调用?
解决方法
我会使用一个小的“视图模型”来保存这样一个命令的信息.
- class ContextAction : INotifyPropertyChanged
- {
- public string Name;
- public ICommand Action;
- public Brush Icon;
- }
在您的视图模型中进行收集,应该获得上下文的动作
- ObservableCollection<ContextAction> Actions {get;set;}
并简单地将此集合绑定到您的ContextMenu.
- <Grid.ContextMenu>
- <ContextMenu ItemsSource="{Binding Actions}/>
上下文菜单项的ItemTemplate现在可以访问名称,命令以及您可能需要的其他任何内容.更改CommandParameter也可能是有用的,以便它将使用动作拥有元素调用命令,而不是使用动作本身.