简体   繁体   中英

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM