我有一个MenuItem样式:
<Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MenuItem}">
<Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"
Height="22" SnapsToDevicePixels="true">
<Grid Margin="-1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="4"/>
<ColumnDefinition SharedSizeGroup="MenuItemIGTColumnGroup" Width="Auto"/>
</Grid.ColumnDefinitions>
<ContentPresenter x:Name="menuHeaderContainer" Grid.Column="0"
ContentSource="Header" HorizontalAlignment="Left"
Margin="{TemplateBinding Padding}" RecognizesAccessKey="True"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="Center"/>
<TextBlock x:Name="menuGestureText" Grid.Column="2"
Margin="{TemplateBinding Padding}" Opacity="0.7" Text="{TemplateBinding InputGestureText}"
VerticalAlignment="Center"/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter Property="Background" TargetName="templateRoot" Value="Black"/>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsHighlighted" Value="True"/>
<Condition Property="IsEnabled" Value="False"/>
</MultiTrigger.Conditions>
<Setter Property="Background" TargetName="templateRoot" Value="Red"/>
<Setter Property="BorderBrush" TargetName="templateRoot" Value="Black"/>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
我的控制权是:
<Grid>
<Menu VerticalAlignment="Center" HorizontalAlignment="Center">
<MenuItem Header="Header">
<MenuItem Header="Second Level"/>
</MenuItem>
</Menu>
当鼠标悬停在menuitem上时,我愿意设置一种新的风格,背景将为黑色。我的风格有效但只有二级菜单。
当鼠标悬停在二级菜单项上时,我的风格有效(当鼠标悬停在它上面时它会变黑):
为什么我的风格无法在第一级MenuItem工作?
答案 0 :(得分:1)
顶级MenuItem和Sub-MenuItems的控制模板是不同的。顶级MenuItem还需要定义SubMenu项目的弹出方式。
您可以为每种类型的菜单项编写多个ControlTemplate。然后使用以下Style设置MenuItem样式:
<Style x:Key="{x:Type MenuItem}" TargetType="MenuItem">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Style.Triggers>
<Trigger Property="Role" Value="TopLevelHeader">
<Setter Property="Template" Value="{StaticResource {x:Static MenuItem.TopLevelHeaderTemplateKey}}"/>
<Setter Property="Grid.IsSharedSizeScope" Value="true"/>
</Trigger>
<Trigger Property="Role" Value="TopLevelItem">
<Setter Property="Template"
Value="{StaticResource {x:Static MenuItem.TopLevelItemTemplateKey}}"/>
</Trigger>
<Trigger Property="Role" Value="SubmenuHeader">
<Setter Property="Template"
Value="{StaticResource {x:Static MenuItem.SubmenuHeaderTemplateKey}}"/>
</Trigger>
<Trigger Property="Role" Value="SubmenuItem">
<Setter Property="Template"
Value="{StaticResource {x:Static MenuItem.SubmenuItemTemplateKey}}"/>
</Trigger>
</Style.Triggers>
</Style>
&#13;
有关详细信息,请参阅此post