Chris Dolan
Chris Dolan

Reputation: 8963

How do I reuse item children via a style in XAML?

I have a WPF submenu that I want to reuse in a few places in my XAML. It's a collection of eight <MenuItem> elements with some complicated bindings that I don't want to copy/paste. However, the holder is different in each case: in one place the parent is a <Menu>, in another place the parent is a <MenuItem> in a <ContextMenu>.

I've been experimenting with <Setter Property="Items"> in my <Style> but I think maybe I'm on the wrong track.

To make it concrete, I'm trying to reduce the 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>

Upvotes: 1

Views: 596

Answers (1)

dzavala
dzavala

Reputation: 988

How about something like this:

You'll need to create the following collection in your resource dictionary:

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

You'll 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>

Upvotes: 2

Related Questions