如果我为菜单项添加一个子菜单,那么子菜单的样式将无法正确应用。此时只能对菜单项进行样式设置,而无法对实际的子菜单进行样式设置。因此,无法更改
IsMouseOver
样式,只能保持Windows主题的默认设置。如何设置子菜单的样式? <Style TargetType="{x:Type MenuItem}">
<Setter Property="Background" Value="#0f3c5a"></Setter>
<Setter Property="Foreground" Value="White"></Setter>
<Style.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter Property="Background" Value="Black"></Setter>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="LightGray"></Setter>
</Trigger>
</Style.Triggers>
</Style>
<Style TargetType="{x:Type ContextMenu}">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContextMenu}">
<!--Here is where you change the border thickness to zero on the menu-->
<Border BorderThickness="0" x:Name="Border" >
<StackPanel ClipToBounds="True" Orientation="Vertical"
IsItemsHost="True"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="Border" Property="Background" Value="#5082a4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然后菜单的部分可以这样做
<ContextMenu Closed="ContextMenu_Closed" >
<MenuItem Command="k:Window1.NewCommand" >
<MenuItem Command="k:Window1.DeleteCommand"/>
</MenuItem>
...
在NewCommand层中的所有内容都已经被正确地样式化了,在查看DeleteCommand时,菜单项本身也已被正确地样式化,但实际的菜单却使用了Windows主题的默认样式,目前我还没有发现覆盖它的方法。最重要的是要让子菜单的IsMouseOver状态保持与主菜单结构相同的外观和感觉。