Here is the default ControlTemplate of ContextMenu in
It always changes its background to blue as the image above.
What's wrong with it? I want to change the background to my favorite color while I hover it. How can I achieve this?
CodePudding user response:
You need to (entirely) re-template the MenuItem
in the ContextMenu
, e.g.:
<ContextMenu>
<ContextMenu.Resources>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MenuItem}">
<Border x:Name="templateRoot" SnapsToDevicePixels="true"
BorderThickness="{TemplateBinding Control.BorderThickness}"
Background="{TemplateBinding Control.Background}"
BorderBrush="{TemplateBinding Control.BorderBrush}">
<Grid Margin="-1">
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="22" SharedSizeGroup="MenuItemIconColumnGroup" Width="Auto"/>
<ColumnDefinition Width="13"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="30"/>
<ColumnDefinition SharedSizeGroup="MenuItemIGTColumnGroup" Width="Auto"/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<ContentPresenter x:Name="Icon" ContentSource="Icon"
SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" VerticalAlignment="Center"
HorizontalAlignment="Center" Width="16" Height="16" Margin="3"/>
<Border x:Name="GlyphPanel" Visibility="Hidden" Height="22" Width="22" VerticalAlignment="Center"
HorizontalAlignment="Center" Background="#3D26A0DA" BorderBrush="#3D26A0DA"
BorderThickness="1" ClipToBounds="false" Margin="-1,0,0,0">
<Path x:Name="Glyph" Data="F1 M 10.0,1.2 L 4.7,9.1 L 4.5,9.1 L 0,5.2 L 1.3,3.5 L 4.3,6.1L 8.3,0 L 10.0,1.2 Z" FlowDirection="LeftToRight" Height="11" Width="10"
Fill="#FF212121"/>
</Border>
<ContentPresenter x:Name="menuHeaderContainer" Grid.Column="2" HorizontalAlignment="Left" VerticalAlignment="Center"
ContentSource="Header" RecognizesAccessKey="true" Margin="{TemplateBinding Control.Padding}"
SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"/>
<TextBlock x:Name="menuGestureText" Grid.Column="4" Text="{TemplateBinding MenuItem.InputGestureText}"
Margin="{TemplateBinding Control.Padding}" VerticalAlignment="Center" Opacity="0.7"/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Value="{x:Null}" Property="MenuItem.Icon">
<Setter TargetName="Icon" Property="UIElement.Visibility" Value="Collapsed"/>
</Trigger>
<Trigger Property="MenuItem.IsChecked" Value="true">
<Setter TargetName="GlyphPanel" Property="UIElement.Visibility" Value="Visible"/>
<Setter TargetName="Icon" Property="UIElement.Visibility" Value="Collapsed"/>
</Trigger>
<Trigger Property="MenuItem.IsHighlighted" Value="true">
<Setter TargetName="templateRoot" Value="LightGray" Property="Border.Background"/>
<Setter TargetName="templateRoot" Value="Red" Property="Border.BorderBrush"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ContextMenu.Resources>
<TextBlock>123</TextBlock>
</ContextMenu>