问题描述
我正在尝试为 ContexMenu 设置默认样式,并且我想在样式内将默认 GroupStyle 设置为 ContexMenu.像这样:
I'm Trying to set default style for ContexMenu and I want to set default GroupStyle to ContexMenu inside the style. Something like this:
<Setter Property="ItemsControl.GroupStyle">
<Setter.Value>
<GroupStyle>
<...>
</GroupStyle>
</Setter.Value>
</Setter>
但编译器提示错误:在 ItemsControl 上找不到 GroupStyle.
But the compiler say error: it can't find GroupStyle on ItemsControl.
但是,在代码中我可以简单地做:
However ,in code I can do simply:
ContextMenu contextMenu;
contextMenu.GroupStyle.Add(someSavedStyle);
我如何在 xaml 中实现这一点?
How can I achieve this in xaml?
提前致谢!
推荐答案
实际上,通过一些额外的工作可以完成:
无需将 ContexMenu
的模板设置为 ItemsPresenter
,您可以将其设置为适合您数据的控件.在这种情况下,您可以将其设置为Menu
.就像这样:
Actually, with some extra work it can be done:
Instead of setting the template of ContexMenu
to ItemsPresenter
, you can set it to control that will fit you data. In this case , you can set it to Menu
. Just like this:
<Style TargetType="ContextMenu">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContextMenu">
<Border>
<Menu ItemsSource="{TemplateBinding ItemsSource}">
<Menu.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<StackPanel>
<Border Background="Black">
<ItemsPresenter/>
</Border>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</Menu.GroupStyle>
<Menu.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel></StackPanel>
</ItemsPanelTemplate>
</Menu.ItemsPanel>
</Menu>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
现在,虽然 GroupStyle
是只读的,但我们可以通过 PropertyElement
设置它:-)
Now, though the GroupStyle
is readonly, we can set it through PropertyElement
:-)
为了准确地获得ContexMenu
的MenuItem
的感觉,您可以调整MenuItem
In order to get exactly the feel of MenuItem
of ContexMenu
you can adjust the style of MenuItem
这篇关于在 xaml 上设置 GroupStyle 内部样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!