【发布时间】:2019-04-25 03:10:25
【问题描述】:
我目前正在尝试在 WPF/XAML 中设置 MenuItem 对象的样式,但我不知道如何为 MenuItem 输出子菜单。需要明确的是,这就是我所追求的:
这就是我目前的 MenuItem 样式:
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Background" Value="{StaticResource GridLightColour}"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="FontFamily" Value="{StaticResource Exo2Light}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="ScrollViewer.PanningMode" Value="Both"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MenuItem}">
<Grid SnapsToDevicePixels="true">
<DockPanel>
<Border x:Name="ContentBorder" BorderThickness="1" BorderBrush="{StaticResource GridLightColour}" Background="{StaticResource GridLightColour}">
<ContentPresenter x:Name="Content" ContentSource="Header" Margin="7,0,0,0" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</DockPanel>
<Popup x:Name="Popup" AllowsTransparency="true" Focusable="false" HorizontalOffset="0" IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" Placement="Bottom" VerticalOffset="-1">
<Border BorderThickness="0" BorderBrush="{StaticResource ButtonColour}" Background="{StaticResource GridLightColour}">
<ScrollViewer x:Name="SubMenuScrollViewer" CanContentScroll="true" Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}">
<Grid RenderOptions.ClearTypeHint="Enabled">
<ItemsPresenter x:Name="ItemsPresenter" Grid.Column="0" KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="true" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" KeyboardNavigation.TabNavigation="Cycle"/>
</Grid>
</ScrollViewer>
</Border>
</Popup>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource MenuButtonMouseOverColour}" TargetName="ContentBorder"/>
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Foreground" Value="{StaticResource ButtonMouseOverColour}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
最好的方法是什么?
【问题讨论】:
-
你想用
ControlTemplate改变菜单结构的哪一部分? -
@BradleyUffner 我正在尝试添加某种方式来构建子菜单项(就像在屏幕截图中一样,如果我将鼠标悬停在“新建”按钮上,它会在右侧打开另一个菜单) .当前的
ControlTemplate适用于第一级菜单项 (imgur.com/S4bclJv) 但如果我尝试在 XAML 中添加另一个级别,我会得到子菜单项显示在下方而不是侧面,如下所示: imgur.com/S4bclJv -
@Step 您根本不必为此修改模板,
MenuItem默认处理它。只需将 MenuItem 相互嵌套,我一直都这样做。