WPF optical style of dynamically created MenuItem-

2019-04-07 06:13发布

问题:

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

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?

Here is the code I use:

<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>

回答1:

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}}" />

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.



回答2:

Try wrapping the Seperator in a MenuItem

<ControlTemplate>
  <MenuItem>
    <MenuItem.Header>
      <Separator />
    </MenuItem.Header>
  </MenuItem>
</ControlTemplate>


标签: wpf mvvm