c# – 上下文菜单的WPF子菜单

前端之家收集整理的这篇文章主要介绍了c# – 上下文菜单的WPF子菜单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果上下文菜单在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来设置子菜单的样式.

猜你在找的C#相关文章