WPF菜单-如何对顶级项目使用其他模板 [英] WPF Menu - How to use a different template for top-level items
问题描述
我想根据项目是否为顶级"项目将不同的模板应用于WPF菜单控件.特别是,我希望顶级项目的文本在上方 较大,其他项目在文本的左侧 较小.
I would like to apply different templates to my WPF menu control depending on whether the item is a "top level" item or not. In particular, I want a larger icon above the text for top-level items and a smaller icon to the left of the text for the other items.
这是我现在正在使用的(有效的)XAML,它可以正确格式化顶级项目,但使其他项目看起来很傻且太大:
This is the (working) XAML I'm using now, which correctly formats the top-level items but leaves the other items looking silly and too-large:
<WrapPanel Height="Auto">
<Menu ItemsSource="{Binding DataContext.EventMenu.TopLevel, ElementName=UserControl}">
<Menu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="IsEnabled" Value="true"/>
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter" Value="{Binding EventType}"/>
</Style>
</Menu.ItemContainerStyle>
<Menu.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image Grid.Row="0" Width="32" Height="32" Margin="5" VerticalAlignment="Center" Source="{Binding Icon32}"/>
<TextBlock Grid.Row="1" Margin="5" Text="{Binding Name}"/>
</Grid>
</HierarchicalDataTemplate>
</Menu.ItemTemplate>
</Menu>
</WrapPanel>
我希望其他项目具有这样的模板:
I'd like the other items to have a template like this:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Height="*"/>
<ColumnDefinition Height="Auto"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Width="16" Height="16" Margin="5" VerticalAlignment="Center" Source="{Binding Icon16}"/>
<TextBlock Grid.Column="1" Margin="5" Text="{Binding Name}"/>
</Grid>
我如何有两个不同的模板,它们以顶级"来区分.我希望不必添加一个属性来指示哪个是顶级项目,但是在必要时可以这样做.
How can I have two different templates distinguished by "top-levelness". I would prefer not to have to add a property to indicate which is a top-level item, but can do so if necessary.
推荐答案
您应该为菜单控件创建两种样式(在单独的资源字典中).一种是样式键(用于顶级项),另一种是样式键(不包含键),以便将其作为默认样式.因此,您只需要在顶级项目中显式设置样式即可.
You should create two styles for the menu control (in a separate resource dictionary). One is with a style key (for the top-level items) and another one without a key so that one will be the default style. Therefore you need to set the style explicitly only in the top-level items.
这篇关于WPF菜单-如何对顶级项目使用其他模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!