如果上下文菜单在xaml中是“硬编码的”,则很容易添加子菜单.例如:
<ContextMenu> <MenuItem Header="Comm1" Command="{Binding Blabla1}"> <MenuItem Header="SubComm1" Command="{Binding Blabla2}"></MenuItem> </MenuItem> <MenuItem Command="Comm2"></MenuItem> <MenuItem Command="Comm3"></MenuItem> </ContextMenu>
这意味着,ContextMenu有三个元素(Comm1,Comm2和Comm3),Comm1有子菜单SubComm1.
我让ContextMenu更加灵活:
<ContextMenu ItemsSource="{Binding ContextMenuItemsSource}"> <ContextMenu.ItemContainerStyle> <Style TargetType="MenuItem"> <Setter Property="Header" Value="{Binding ContextMenuCommandHeader}"></Setter> <Setter Property="Command" Value="{Binding ContextMenuCommand}"></Setter> </Style> </ContextMenu.ItemContainerStyle> </ContextMenu>
基本上我在ContextMenu中可以有任意数量的元素,任何元素都可以有任何命令.如何将子菜单添加到ContextMenu元素?
解决方法
您可以将MenuItem.ItemsSource设置为嵌套集合.这将为任何menuitem生成子菜单.为此,支持MenuItem的模型应该包含子菜单集合
<ContextMenu ItemsSource="{Binding ContextMenuItemsSource}"> <ContextMenu.ItemContainerStyle> <Style TargetType="MenuItem"> <Setter Property="ItemsSource" Value="{Binding ContextMenuSubItems}"></Setter> <Setter Property="Header" Value="{Binding ContextMenuCommandHeader}"></Setter> <Setter Property="Command" Value="{Binding ContextMenuCommand}"></Setter> </Style> </ContextMenu.ItemContainerStyle> </ContextMenu>
同样,您可以设置MenuItem.ItemContainerStyle和MenuItem.ItemTemplate来设置子菜单的样式.