How to reuse XAML style children?

I have a WPF submenu that I want to reuse in several places in my XAML. This is a set of eight <MenuItem> elements with some complex links that I don't want to copy / paste. However, the holder is different in each case: in one place, the parent element is <Menu> , in another place the parent element is <MenuItem> in <ContextMenu> .

I experimented with <Setter Property="Items"> in my <Style> , but I think that maybe I'm wrong.

To make this specific, I am trying to reduce code duplication from something like this:

 <Menu> <MenuItem Header="Details" IsCheckable="True" ... /> <MenuItem Header="List" IsCheckable="True" ... /> <MenuItem Header="Thumbnails" IsCheckable="True" ... /> ... </Menu> ... <ContextMenu> <MenuItem Header="View"> <MenuItem Header="Details" IsCheckable="True" ... /> <MenuItem Header="List" IsCheckable="True" ... /> <MenuItem Header="Thumbnails" IsCheckable="True" ... /> ... </MenuItem> </ContextMenu> 
+1
source share
1 answer

How about something like this:

In your resource dictionary, you will need to create the following collection:

 <Collections:ArrayList x:Key="MenuItems" x:Shared="false"> <MenuItem Header="Details" /> <MenuItem Header="List" /> <MenuItem Header="Thumbnails" /> </Collections:ArrayList> 

You need to add the following namespace:

 xmlns:Collections="clr-namespace:System.Collections;assembly=mscorlib" 

...

And then just use the collection:

 <Menu ItemsSource="{StaticResource MenuItems}" /> 

...

 <ContextMenu> <MenuItem Header="View" ItemsSource="{StaticResource MenuItems}" /> </ContextMenu> 
+2
source

All Articles