Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF optical style of dynamically created MenuItem-Separator in MVVM

Tags:

mvvm

wpf

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>
like image 745
HCL Avatar asked Sep 09 '10 09:09

HCL


1 Answers

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.

like image 116
Quartermeister Avatar answered Oct 04 '22 08:10

Quartermeister