c# – MVVM中的ContextMenu
发布时间:2020-12-15 03:55:15 所属栏目:百科 来源:网络整理
导读:我想绑定一个上下文菜单到一个命令列表. Grid.ContextMenu ContextMenu ItemsSource="{Binding ItemContextCommands,Converter={StaticResource commandToStringConverter}}" ContextMenu.ItemTemplate DataTemplate DataType="MenuItem" MenuItem Command="
我想绑定一个上下文菜单到一个命令列表.
<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也可能是有用的,以便它将使用动作拥有元素调用命令,而不是使用动作本身. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |