WPF optical style dynamically created MenuItem-Separator in MVVM

I have a MenuItem that dynamically creates submenu items from ItemsSource -property.

For grouping, I have separators in the menu. A separator is created for each null entry in the ItemsSource collection using the MenuItem.ItemContainerStyle checklist.

This works great, but the separator is not as optical as the other separators that fit into the Items collection on the menu.

Is there a way to change the appearance of the separator so that it looks equal to the "normal" separators of the menu items?

Here is the code I'm using:

 <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> 
+7
wpf mvvm
source share
2 answers

As a key, a style is declared, which is declared in System.Resources with MenuItem.SeparatorStyleKey . The parent MenuItem usually sets the style for children like Separator, but since yours is the MenuItem, it will not, so you have to do it manually:

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

You can also read Bea Stollnitz's blog post, "How to Insert Separator Objects into a DataImem?" for a different approach.

+15
source share

Try wrapping Seperator in MenuItem

 <ControlTemplate> <MenuItem> <MenuItem.Header> <Separator /> </MenuItem.Header> </MenuItem> </ControlTemplate> 
0
source share

All Articles