在 WPF 中单击时更改菜单背景

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24684392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:07:40  来源:igfitidea点击:

Change the Menu background when clicked in WPF

c#wpfmenumenuitem

提问by Vahid

I'm using the below code to style a Menu. I have been able to change the background when the Mouseis Overthe menu. But I don't know how to change its Backgroundwhen it is clicked.

我正在使用下面的代码来设计一个Menu. 当MouseOver菜单时,我已经能够更改背景。但是我不知道如何在Background单击时更改它。

<Window x:Class="WpfApplication11.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>

        <SolidColorBrush x:Key="NormalColor">White</SolidColorBrush>
        <SolidColorBrush x:Key="HoverColor">LightGray</SolidColorBrush>
        <SolidColorBrush x:Key="ClickedColor">DarkGray</SolidColorBrush>

        <Style x:Key="{x:Type Menu}" TargetType="Menu">
            <Setter Property="OverridesDefaultStyle" Value="True"/>
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Menu">
                        <Border x:Name="MainMenu" Background="{StaticResource NormalColor}"
                                BorderBrush="Black"
                                BorderThickness="1">
                            <StackPanel ClipToBounds="True" Orientation="Horizontal" IsItemsHost="True"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="MainMenu" Property="Background" Value="{StaticResource HoverColor}"/>
                            </Trigger>                           
                        </ControlTemplate.Triggers>                        
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <Menu Width="30" Height="20" Margin="10, 10, 5, 5" HorizontalAlignment="Left" Background="White">
            <MenuItem Header="_File">
                <MenuItem Header="_New"/>
                <MenuItem Header="_Open"/>
                <MenuItem Header="_Close"/>
            </MenuItem>
        </Menu>
    </Grid>
</Window>

Update:I have tried the following code but it didn't work either.

更新:我尝试了以下代码,但它也不起作用。

<Trigger Property="IsFocused" Value="True">
    <Setter TargetName="MainMenu" Property="Background" Value="{StaticResource ClickedColor}"/>
</Trigger

回答by J.H.

You could try using IsKeyboardFocusWithin.

您可以尝试使用 IsKeyboardFocusWithin。

<Trigger Property="IsKeyboardFocusWithin" Value="True">
    <Setter TargetName="MainMenu" Property="Background" Value="{StaticResource ClickedColor}"/>
</Trigger>

Here is your code with the IsKeyboardFocusWithin trigger added. I changed the ClickedColor to Purple so it is easier to see. I added Name="mm" to your menu. I added a stack panel with textblocks bound to mm.IsFocused and mm.IsKeyboardFocusWithin so you can visually see what they are set to and when it changes.

这是添加了 IsKeyboardFocusWithin 触发器的代码。我将 ClickedColor 更改为紫色,以便更容易查看。我在你的菜单中添加了 Name="mm"。我添加了一个带有绑定到 mm.IsFocused 和 mm.IsKeyboardFocusWithin 的文本块的堆栈面板,以便您可以直观地看到它们的设置以及更改的时间。

<Window x:Class="WpfApplication11.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>

    <SolidColorBrush x:Key="NormalColor">White</SolidColorBrush>
    <SolidColorBrush x:Key="HoverColor">LightGray</SolidColorBrush>
    <SolidColorBrush x:Key="ClickedColor">Purple</SolidColorBrush>

    <Style x:Key="{x:Type Menu}" TargetType="Menu">
        <Setter Property="OverridesDefaultStyle" Value="True"/>
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Menu">
                    <Border x:Name="MainMenu" Background="{StaticResource NormalColor}"
                            BorderBrush="Black"
                            BorderThickness="1">
                        <StackPanel ClipToBounds="True" Orientation="Horizontal" IsItemsHost="True"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="MainMenu" Property="Background" Value="{StaticResource HoverColor}"/>
                        </Trigger>
                        <Trigger Property="IsKeyboardFocusWithin" Value="True">
                            <Setter TargetName="MainMenu" Property="Background" Value="{StaticResource ClickedColor}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <Menu Width="30" Height="20" Margin="10, 10, 5, 5" HorizontalAlignment="Left" Background="White" VerticalAlignment="Top" Name="mm">
        <MenuItem Header="_File">
            <MenuItem Header="_New"/>
            <MenuItem Header="_Open"/>
            <MenuItem Header="_Close"/>
        </MenuItem>
    </Menu>
    <StackPanel VerticalAlignment="Center">
        <TextBlock Text="menu.IsFocused:" />
        <TextBlock Text="{Binding ElementName=mm, Path=IsFocused}" />
        <TextBlock Text="menu.IsKeyboardFocusWithin:" />
        <TextBlock Text="{Binding ElementName=mm, Path=IsKeyboardFocusWithin}" />
    </StackPanel>
</Grid>

OK, for the menu item... try this:

好的,对于菜单项...试试这个:

<Window x:Class="WpfApplication11.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>

    <SolidColorBrush x:Key="NormalColor">White</SolidColorBrush>
    <SolidColorBrush x:Key="HoverColor">LightGray</SolidColorBrush>
    <SolidColorBrush x:Key="ClickedColor">Purple</SolidColorBrush>

    <Style x:Key="{x:Type Menu}" TargetType="Menu">
        <Setter Property="OverridesDefaultStyle" Value="True"/>
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Menu">
                    <Border x:Name="MainMenu" Background="{StaticResource NormalColor}"
                            BorderBrush="Black"
                            BorderThickness="1">
                        <StackPanel ClipToBounds="True" Orientation="Horizontal" IsItemsHost="True"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="MainMenu" Property="Background" Value="{StaticResource HoverColor}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <ControlTemplate x:Key="MenuItemControlTemplate1" TargetType="{x:Type MenuItem}">
        <Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
            <Grid VerticalAlignment="Center">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <ContentPresenter x:Name="Icon" Content="{TemplateBinding Icon}" ContentSource="Icon" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/>
                <Path x:Name="GlyphPanel" Data="F1M10,1.2L4.7,9.1 4.5,9.1 0,5.2 1.3,3.5 4.3,6.1 8.3,0 10,1.2z" Fill="{TemplateBinding Foreground}" FlowDirection="LeftToRight" Margin="3" Visibility="Collapsed" VerticalAlignment="Center"/>
                <ContentPresenter ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" Grid.Column="1" ContentStringFormat="{TemplateBinding HeaderStringFormat}" ContentSource="Header" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                <Popup x:Name="PART_Popup" AllowsTransparency="True" Focusable="False" IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" Placement="Bottom">
                    <Border x:Name="SubMenuBorder" BorderBrush="#FF999999" BorderThickness="1" Background="#FFF0F0F0" Padding="2">
                        <ScrollViewer x:Name="SubMenuScrollViewer" Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}">
                            <Grid RenderOptions.ClearTypeHint="Enabled">
                                <Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                    <Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=SubMenuBorder}" Height="{Binding ActualHeight, ElementName=SubMenuBorder}" Width="{Binding ActualWidth, ElementName=SubMenuBorder}"/>
                                </Canvas>
                                <Rectangle Fill="#FFD7D7D7" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/>
                                <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" KeyboardNavigation.TabNavigation="Cycle"/>
                            </Grid>
                        </ScrollViewer>
                    </Border>
                </Popup>
            </Grid>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="IsSuspendingPopupAnimation" Value="True">
                <Setter Property="PopupAnimation" TargetName="PART_Popup" Value="None"/>
            </Trigger>
            <Trigger Property="Icon" Value="{x:Null}">
                <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
            </Trigger>
            <Trigger Property="IsChecked" Value="True">
                <Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/>
                <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
            </Trigger>
            <Trigger Property="IsHighlighted" Value="True">
                <Setter Property="Background" TargetName="templateRoot" Value="#3D26A0DA"/>
                <Setter Property="BorderBrush" TargetName="templateRoot" Value="#FF26A0DA"/>
            </Trigger>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="#FF707070"/>
                <Setter Property="Fill" TargetName="GlyphPanel" Value="#FF707070"/>
            </Trigger>
            <Trigger Property="CanContentScroll" SourceName="SubMenuScrollViewer" Value="False">
                <Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=SubMenuScrollViewer}"/>
                <Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=SubMenuScrollViewer}"/>
            </Trigger>
            <Trigger Property="IsKeyboardFocusWithin" Value="True">
                <Setter TargetName="templateRoot" Property="Background" Value="{StaticResource ClickedColor}" />
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</Window.Resources>
<Grid>
    <Menu Width="100" Height="20" Margin="10, 10, 5, 5" HorizontalAlignment="Left" Background="White" VerticalAlignment="Top">
        <MenuItem Header="_File" Name="mm" Template="{DynamicResource MenuItemControlTemplate1}">
            <MenuItem Header="_New"/>
            <MenuItem Header="_Open"/>
            <MenuItem Header="_Close"/>
        </MenuItem>
        <MenuItem Header="_Edit" Template="{DynamicResource MenuItemControlTemplate1}">
            <MenuItem Header="_Copy"/>
            <MenuItem Header="_Cut"/>
            <MenuItem Header="_Paste"/>
        </MenuItem>
    </Menu>
    <StackPanel VerticalAlignment="Center">
        <TextBlock Text="menuitem.IsFocused:" />
        <TextBlock Text="{Binding ElementName=mm, Path=IsFocused}" />
        <TextBlock Text="menuitem.IsKeyboardFocusWithin:" />
        <TextBlock Text="{Binding ElementName=mm, Path=IsKeyboardFocusWithin}" />
    </StackPanel>
</Grid>

回答by Sheridan

You just need to add an event handler to the Menu.PreviewMouseDownevent and change the Backgroundthere. Try this:

您只需要向事件添加一个事件处理程序Menu.PreviewMouseDown并在Background那里更改。尝试这个:

<Menu Width="30" Height="20" Margin="10, 10, 5, 5" HorizontalAlignment="Left" 
    Background="White" PreviewMouseDown="Menu_PreviewMouseDown">
    <MenuItem Header="_File">
        <MenuItem Header="_New"/>
        <MenuItem Header="_Open"/>
        <MenuItem Header="_Close"/>
    </MenuItem>
</Menu>

...

...

private void Menu_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    Menu menu = (Menu)sender;
    menu.Background = Brushes.DarkGray;
}

If you just want it to change colour while the mouse button is held down, then you could attach a handler to the MenuItem.PreviewMouseUpevent to change it back to White.

如果您只想在按住鼠标按钮时更改颜色,则可以将处理程序附加到MenuItem.PreviewMouseUp事件以将其更改回White.



UPDATE >>>

更新 >>>

You can add a handler to the MouseLeaveevent to change the Backgroundback when the mouse cursor leaves the bounds of theMenu`. Try this:

您可以向MouseLeave事件添加处理程序以更改背景back when the mouse cursor leaves the bounds of the菜单`。尝试这个:

<Menu Width="30" Height="20" Margin="10, 10, 5, 5" HorizontalAlignment="Left" 
    Background="White" PreviewMouseDown="Menu_PreviewMouseDown" 
    MouseLeave="Menu_MouseLeave">
    <MenuItem Header="_File">
        <MenuItem Header="_New"/>
        <MenuItem Header="_Open"/>
        <MenuItem Header="_Close"/>
    </MenuItem>
</Menu>

...

...

private void Menu_MouseLeave(object sender, MouseEventArgs e)
{
    Menu menu = (Menu)sender;
    menu.Background = Brushes.White;
}

回答by Troels Larsen

You can rework the Template for the MenuItem (not the Menu). To reproduce what I did:

您可以重新设计 MenuItem(而不是 Menu)的模板。重现我所做的:

  1. Select a MenuItem in XAML
  2. Right click it in the designer.
  3. Select 'Edit Template'
  4. Select 'Edit a Copy'
  5. Edit the 'MenuItem.Highlight.Background' SolidColorBrush to a new color of your choosing. (I chose 'Red')
  6. Remove the Key from the style for the MenuItem.
  1. 在 XAML 中选择一个菜单项
  2. 在设计器中右键单击它。
  3. 选择“编辑模板”
  4. 选择“编辑副本”
  5. 将“MenuItem.Highlight.Background”SolidColorBrush 编辑为您选择的新颜色。(我选择了“红色”)
  6. 从 MenuItem 的样式中删除 Key。

You will end up with the following resources if you start from scratch:

如果您从头开始,您最终将获得以下资源:

<Window.Resources>
    <SolidColorBrush x:Key="MenuItem.Highlight.Background" Color="Red"/>
    <SolidColorBrush x:Key="MenuItem.Highlight.Border" Color="#FF26A0DA"/>
    <SolidColorBrush x:Key="Menu.Disabled.Foreground" Color="#FF707070"/>
    <SolidColorBrush x:Key="MenuItem.Highlight.Disabled.Background" Color="#0A000000"/>
    <SolidColorBrush x:Key="MenuItem.Highlight.Disabled.Border" Color="#21000000"/>
    <SolidColorBrush x:Key="MenuItem.Selected.Border" Color="#FF26A0DA"/>
    <SolidColorBrush x:Key="MenuItem.Selected.Background" Color="#3D26A0DA"/>
    <Geometry x:Key="Checkmark">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</Geometry>
    <SolidColorBrush x:Key="Menu.Static.Foreground" Color="#FF212121"/>
    <ControlTemplate x:Key="{ComponentResourceKey ResourceId=SubmenuItemTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}" 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 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" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/>
                <Border x:Name="GlyphPanel" BorderBrush="{StaticResource MenuItem.Selected.Border}" BorderThickness="1" Background="{StaticResource MenuItem.Selected.Background}" ClipToBounds="False" HorizontalAlignment="Center" Height="22" Margin="-1,0,0,0" Visibility="Hidden" VerticalAlignment="Center" Width="22">
                    <Path x:Name="Glyph" Data="{StaticResource Checkmark}" Fill="{StaticResource Menu.Static.Foreground}" FlowDirection="LeftToRight" Height="11" Width="10"/>
                </Border>
                <ContentPresenter x:Name="menuHeaderContainer" Grid.Column="2" ContentSource="Header" HorizontalAlignment="Left" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center"/>
                <TextBlock x:Name="menuGestureText" Grid.Column="4" Margin="{TemplateBinding Padding}" Opacity="0.7" Text="{TemplateBinding InputGestureText}" VerticalAlignment="Center"/>
            </Grid>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="Icon" Value="{x:Null}">
                <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
            </Trigger>
            <Trigger Property="IsChecked" Value="True">
                <Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/>
                <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
            </Trigger>
            <Trigger Property="IsHighlighted" Value="True">
                <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Background}"/>
                <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Border}"/>
            </Trigger>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="{StaticResource Menu.Disabled.Foreground}"/>
                <Setter Property="Fill" TargetName="Glyph" Value="{StaticResource Menu.Disabled.Foreground}"/>
            </Trigger>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsHighlighted" Value="True"/>
                    <Condition Property="IsEnabled" Value="False"/>
                </MultiTrigger.Conditions>
                <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Disabled.Background}"/>
                <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Disabled.Border}"/>
            </MultiTrigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
    <SolidColorBrush x:Key="Menu.Static.Border" Color="#FF999999"/>
    <SolidColorBrush x:Key="Menu.Static.Background" Color="#FFF0F0F0"/>
    <SolidColorBrush x:Key="Menu.Static.Separator" Color="#FFD7D7D7"/>
    <Geometry x:Key="UpArrow">M 0,4 L 3.5,0 L 7,4 Z</Geometry>
    <Style x:Key="MenuScrollButton" BasedOn="{x:Null}" TargetType="{x:Type RepeatButton}">
        <Setter Property="ClickMode" Value="Hover"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RepeatButton}">
                    <Border x:Name="templateRoot" BorderBrush="Transparent" BorderThickness="1" Background="Transparent" SnapsToDevicePixels="true">
                        <ContentPresenter HorizontalAlignment="Center" Margin="6" VerticalAlignment="Center"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <MenuScrollingVisibilityConverter x:Key="MenuScrollingVisibilityConverter"/>
    <Geometry x:Key="DownArrow">M 0,0 L 3.5,4 L 7,0 Z</Geometry>
    <Style x:Key="{ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}" BasedOn="{x:Null}" TargetType="{x:Type ScrollViewer}">
        <Setter Property="HorizontalScrollBarVisibility" Value="Hidden"/>
        <Setter Property="VerticalScrollBarVisibility" Value="Auto"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ScrollViewer}">
                    <Grid SnapsToDevicePixels="true">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Border Grid.Column="0" Grid.Row="1">
                            <ScrollContentPresenter CanContentScroll="{TemplateBinding CanContentScroll}" Margin="{TemplateBinding Padding}"/>
                        </Border>
                        <RepeatButton Grid.Column="0" CommandTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" Command="{x:Static ScrollBar.LineUpCommand}" Focusable="false" Grid.Row="0" Style="{StaticResource MenuScrollButton}">
                            <RepeatButton.Visibility>
                                <MultiBinding ConverterParameter="0" Converter="{StaticResource MenuScrollingVisibilityConverter}" FallbackValue="Visibility.Collapsed">
                                    <Binding Path="ComputedVerticalScrollBarVisibility" RelativeSource="{RelativeSource TemplatedParent}"/>
                                    <Binding Path="VerticalOffset" RelativeSource="{RelativeSource TemplatedParent}"/>
                                    <Binding Path="ExtentHeight" RelativeSource="{RelativeSource TemplatedParent}"/>
                                    <Binding Path="ViewportHeight" RelativeSource="{RelativeSource TemplatedParent}"/>
                                </MultiBinding>
                            </RepeatButton.Visibility>
                            <Path Data="{StaticResource UpArrow}" Fill="{StaticResource Menu.Static.Foreground}"/>
                        </RepeatButton>
                        <RepeatButton Grid.Column="0" CommandTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" Command="{x:Static ScrollBar.LineDownCommand}" Focusable="false" Grid.Row="2" Style="{StaticResource MenuScrollButton}">
                            <RepeatButton.Visibility>
                                <MultiBinding ConverterParameter="100" Converter="{StaticResource MenuScrollingVisibilityConverter}" FallbackValue="Visibility.Collapsed">
                                    <Binding Path="ComputedVerticalScrollBarVisibility" RelativeSource="{RelativeSource TemplatedParent}"/>
                                    <Binding Path="VerticalOffset" RelativeSource="{RelativeSource TemplatedParent}"/>
                                    <Binding Path="ExtentHeight" RelativeSource="{RelativeSource TemplatedParent}"/>
                                    <Binding Path="ViewportHeight" RelativeSource="{RelativeSource TemplatedParent}"/>
                                </MultiBinding>
                            </RepeatButton.Visibility>
                            <Path Data="{StaticResource DownArrow}" Fill="{StaticResource Menu.Static.Foreground}"/>
                        </RepeatButton>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <ControlTemplate x:Key="{ComponentResourceKey ResourceId=TopLevelHeaderTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}" TargetType="{x:Type MenuItem}">
        <Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
            <Grid VerticalAlignment="Center">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <ContentPresenter x:Name="Icon" ContentSource="Icon" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/>
                <Path x:Name="GlyphPanel" Data="{StaticResource Checkmark}" Fill="{TemplateBinding Foreground}" FlowDirection="LeftToRight" Margin="3" Visibility="Collapsed" VerticalAlignment="Center"/>
                <ContentPresenter Grid.Column="1" ContentSource="Header" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                <Popup x:Name="PART_Popup" AllowsTransparency="true" Focusable="false" IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" Placement="Bottom" PlacementTarget="{Binding ElementName=templateRoot}">
                    <Border x:Name="SubMenuBorder" BorderBrush="{StaticResource Menu.Static.Border}" BorderThickness="1" Background="{StaticResource Menu.Static.Background}" Padding="2">
                        <ScrollViewer x:Name="SubMenuScrollViewer" Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}">
                            <Grid RenderOptions.ClearTypeHint="Enabled">
                                <Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                    <Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=SubMenuBorder}" Height="{Binding ActualHeight, ElementName=SubMenuBorder}" Width="{Binding ActualWidth, ElementName=SubMenuBorder}"/>
                                </Canvas>
                                <Rectangle Fill="{StaticResource Menu.Static.Separator}" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/>
                                <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="true" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" KeyboardNavigation.TabNavigation="Cycle"/>
                            </Grid>
                        </ScrollViewer>
                    </Border>
                </Popup>
            </Grid>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="IsSuspendingPopupAnimation" Value="true">
                <Setter Property="PopupAnimation" TargetName="PART_Popup" Value="None"/>
            </Trigger>
            <Trigger Property="Icon" Value="{x:Null}">
                <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
            </Trigger>
            <Trigger Property="IsChecked" Value="true">
                <Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/>
                <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
            </Trigger>
            <Trigger Property="IsHighlighted" Value="True">
                <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Background}"/>
                <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Border}"/>
            </Trigger>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="{StaticResource Menu.Disabled.Foreground}"/>
                <Setter Property="Fill" TargetName="GlyphPanel" Value="{StaticResource Menu.Disabled.Foreground}"/>
            </Trigger>
            <Trigger Property="ScrollViewer.CanContentScroll" SourceName="SubMenuScrollViewer" Value="false">
                <Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=SubMenuScrollViewer}"/>
                <Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=SubMenuScrollViewer}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
    <ControlTemplate x:Key="{ComponentResourceKey ResourceId=TopLevelItemTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}" TargetType="{x:Type MenuItem}">
        <Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
            <Grid VerticalAlignment="Center">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <ContentPresenter x:Name="Icon" ContentSource="Icon" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/>
                <Path x:Name="GlyphPanel" Data="{StaticResource Checkmark}" Fill="{StaticResource Menu.Static.Foreground}" FlowDirection="LeftToRight" Margin="3" Visibility="Collapsed" VerticalAlignment="Center"/>
                <ContentPresenter Grid.Column="1" ContentSource="Header" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
            </Grid>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="Icon" Value="{x:Null}">
                <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
            </Trigger>
            <Trigger Property="IsChecked" Value="true">
                <Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/>
                <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
            </Trigger>
            <Trigger Property="IsHighlighted" Value="True">
                <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Background}"/>
                <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Border}"/>
            </Trigger>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="{StaticResource Menu.Disabled.Foreground}"/>
                <Setter Property="Fill" TargetName="GlyphPanel" Value="{StaticResource Menu.Disabled.Foreground}"/>
            </Trigger>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsHighlighted" Value="True"/>
                    <Condition Property="IsEnabled" Value="False"/>
                </MultiTrigger.Conditions>
                <Setter Property="Background" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Disabled.Background}"/>
                <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Disabled.Border}"/>
            </MultiTrigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
    <Geometry x:Key="RightArrow">M 0,0 L 4,3.5 L 0,7 Z</Geometry>
    <ControlTemplate x:Key="{ComponentResourceKey ResourceId=SubmenuHeaderTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}" 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 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" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/>
                <Border x:Name="GlyphPanel" BorderBrush="{StaticResource MenuItem.Highlight.Border}" BorderThickness="1" Background="{StaticResource MenuItem.Highlight.Background}" Height="22" Margin="-1,0,0,0" Visibility="Hidden" VerticalAlignment="Center" Width="22">
                    <Path x:Name="Glyph" Data="{DynamicResource Checkmark}" Fill="{StaticResource Menu.Static.Foreground}" FlowDirection="LeftToRight" Height="11" Width="9"/>
                </Border>
                <ContentPresenter Grid.Column="2" ContentSource="Header" HorizontalAlignment="Left" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center"/>
                <TextBlock Grid.Column="4" Margin="{TemplateBinding Padding}" Opacity="0.7" Text="{TemplateBinding InputGestureText}" VerticalAlignment="Center"/>
                <Path x:Name="RightArrow" Grid.Column="5" Data="{StaticResource RightArrow}" Fill="{StaticResource Menu.Static.Foreground}" HorizontalAlignment="Left" Margin="10,0,0,0" VerticalAlignment="Center"/>
                <Popup x:Name="PART_Popup" AllowsTransparency="true" Focusable="false" HorizontalOffset="-2" IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" Placement="Right" VerticalOffset="-3">
                    <Border x:Name="SubMenuBorder" BorderBrush="{StaticResource Menu.Static.Border}" BorderThickness="1" Background="{StaticResource Menu.Static.Background}" Padding="2">
                        <ScrollViewer x:Name="SubMenuScrollViewer" Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}">
                            <Grid RenderOptions.ClearTypeHint="Enabled">
                                <Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                    <Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=SubMenuBorder}" Height="{Binding ActualHeight, ElementName=SubMenuBorder}" Width="{Binding ActualWidth, ElementName=SubMenuBorder}"/>
                                </Canvas>
                                <Rectangle Fill="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/>
                                <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="true" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" KeyboardNavigation.TabNavigation="Cycle"/>
                            </Grid>
                        </ScrollViewer>
                    </Border>
                </Popup>
            </Grid>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="IsSuspendingPopupAnimation" Value="true">
                <Setter Property="PopupAnimation" TargetName="PART_Popup" Value="None"/>
            </Trigger>
            <Trigger Property="Icon" Value="{x:Null}">
                <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
            </Trigger>
            <Trigger Property="IsChecked" Value="True">
                <Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/>
                <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
            </Trigger>
            <Trigger Property="IsHighlighted" Value="True">
                <Setter Property="Background" TargetName="templateRoot" Value="Transparent"/>
                <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Border}"/>
            </Trigger>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="{StaticResource Menu.Disabled.Foreground}"/>
                <Setter Property="Fill" TargetName="Glyph" Value="{StaticResource Menu.Disabled.Foreground}"/>
                <Setter Property="Fill" TargetName="RightArrow" Value="{StaticResource Menu.Disabled.Foreground}"/>
            </Trigger>
            <Trigger Property="ScrollViewer.CanContentScroll" SourceName="SubMenuScrollViewer" Value="false">
                <Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=SubMenuScrollViewer}"/>
                <Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=SubMenuScrollViewer}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
    <Style TargetType="{x:Type MenuItem}">
        <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
        <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="BorderBrush" Value="Transparent"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="ScrollViewer.PanningMode" Value="Both"/>
        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
        <Setter Property="Template" Value="{DynamicResource {ComponentResourceKey ResourceId=SubmenuItemTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}}"/>
        <Style.Triggers>
            <Trigger Property="Role" Value="TopLevelHeader">
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="BorderBrush" Value="Transparent"/>
                <Setter Property="Foreground" Value="{StaticResource Menu.Static.Foreground}"/>
                <Setter Property="Template" Value="{DynamicResource {ComponentResourceKey ResourceId=TopLevelHeaderTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}}"/>
                <Setter Property="Padding" Value="6,0"/>
            </Trigger>
            <Trigger Property="Role" Value="TopLevelItem">
                <Setter Property="Background" Value="{StaticResource Menu.Static.Background}"/>
                <Setter Property="BorderBrush" Value="{StaticResource Menu.Static.Border}"/>
                <Setter Property="Foreground" Value="{StaticResource Menu.Static.Foreground}"/>
                <Setter Property="Template" Value="{DynamicResource {ComponentResourceKey ResourceId=TopLevelItemTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}}"/>
                <Setter Property="Padding" Value="6,0"/>
            </Trigger>
            <Trigger Property="Role" Value="SubmenuHeader">
                <Setter Property="Template" Value="{DynamicResource {ComponentResourceKey ResourceId=SubmenuHeaderTemplateKey, TypeInTargetAssembly={x:Type MenuItem}}}"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

This looks daunting, but you are basically telling the MenuItem to use another Template other than the one defined in the theme. Personally, I avoid doing such things, as it breaks the themes across the various Windows versions. By doing this, the Menu will look the same on XP, Vista & 8.

这看起来令人生畏,但您基本上是在告诉 MenuItem 使用主题中定义的模板以外的另一个模板。就我个人而言,我避免做这样的事情,因为它打破了各种 Windows 版本的主题。通过这样做,菜单在 XP、Vista 和 8 上看起来是一样的。

You will likely be able to optimize this quite a bit. But I at least recommend you put it in a separate ResourceDictionary.

您可能会对此进行相当多的优化。但我至少建议你把它放在一个单独的 ResourceDictionary 中。