MVVM 中动态创建 MenuItem-Separator 的 WPF 光学样式 [英] WPF optical style of dynamically created MenuItem-Separator in MVVM

查看:38
本文介绍了MVVM 中动态创建 MenuItem-Separator 的 WPF 光学样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MenuItem,它从 ItemsSource 属性动态创建其子菜单项.

I have have a MenuItem that creates its sub-menu-items dynamicly from the ItemsSource-property.

对于分组,我在菜单中有分隔符.分隔符是由 MenuItem.ItemContainerStyle 的 ControlTemplate 为 ItemsSource 集合中的每个空条目创建的.

For grouping, I have Separators in the menu. The separator is created for each null-entry in the ItemsSource-collection by a ControlTemplate of the MenuItem.ItemContainerStyle.

这工作正常,但是分隔符与放置在菜单的项目集合中的其他分隔符的光学样式不同.

This works fine, however has the separator not the same optical style as the other separators have which are placed in a the Items-collection of a menu.

有没有办法改变分隔符的外观,使其看起来与普通"菜单项分隔符相同?

Is there a way to change the look of the separator so that it looks equal to the "normal" menu-item-separators?

这是我使用的代码:

<MenuItem.ItemContainerStyle>
  <Style TargetType="MenuItem">
    <Setter Property="Header" Value="{Binding Title}"/>
    <Setter Property="Command" Value="{Binding Command}"/>
    <Style.Triggers>
        <DataTrigger Binding="{Binding }" Value="{x:Null}">
            <Setter Property="Template" >
                <Setter.Value>
                    <ControlTemplate>
                        <Separator /> <!-- THIS SEPARATOR IS NOT SHOWN AS COMMON MENUITEM-SEPARATORS ARE -->
                    </ControlTemplate>                                        
                </Setter.Value>
            </Setter>
        </DataTrigger>                            
    </Style.Triggers>
  </Style>
</MenuItem.ItemContainerStyle>

推荐答案

在 System.Resources 中声明了一个样式 MenuItem.SeparatorStyleKey 作为键.父 MenuItem 通常在 Separator 类型的子项上设置样式,但由于您的是 MenuItem,因此不会,因此您必须手动进行:

There is a Style that is declared in System.Resources with MenuItem.SeparatorStyleKey as the key. The parent MenuItem normally sets the style on children of type Separator, but since yours is a MenuItem, it won't, so you will have to do it manually:

<Separator Style="{StaticResource {x:Static MenuItem.SeparatorStyleKey}}" />

您可能还想阅读 Bea Stollnitz 的博客条目 "如何将 Separator 对象插入到数据绑定 MenuItem?" 用于另一种方法.

You may also want to read Bea Stollnitz's blog entry "How do I insert Separator objects in a data bound MenuItem?" for another approach.

这篇关于MVVM 中动态创建 MenuItem-Separator 的 WPF 光学样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆