Search code examples
c#wpfmenuitemcompositecollection

Populating MenuItem with composite collection "doubling" up


I'm trying to populate a menu item with a collection of children items. That was easy, however I need to add an extra that's always present that performs an "add" operation. I used a composite collection to add this on to the existing collection of items that need to be displayed.

Here's the code:

<MenuItem Header="Time Ranges" x:Name="TimeRangesMenuItem"
        Background="{StaticResource TitleBarButtonBackgroundBrush}"
        Margin="2">
    <MenuItem.Resources>
        <CollectionViewSource Source="{Binding ElementName=TimeRangesMenuItem, Path=DataContext.TimeSpans}" x:Key="TimeSpanMenuItems" />
    </MenuItem.Resources>
    <MenuItem.ItemsSource>
        <CompositeCollection>
            <CollectionContainer Collection="{Binding Source={StaticResource TimeSpanMenuItems}}" />
            <Separator />
            <MenuItem Header="Add New" cal:Message.Attach="NewTimeSpan()" />
        </CompositeCollection>
    </MenuItem.ItemsSource>
    <MenuItem.ItemTemplate>
        <ItemContainerTemplate>
            <MenuItem Header="{Binding Name}" cal:Message.Attach="ConfigureTimeSpan()" />
        </ItemContainerTemplate>
    </MenuItem.ItemTemplate>
</MenuItem>

It works, almost. The DataContext.TimeSpans ViewModel's I'm trying to display are "nested" inside two MenuItems, rather than just populating one, so I get this strange behavior (this only has a single TimeSpanViewModel "Time Span":

Mouse outside the "inner" MenuItem. Note, the inner one is functional if you press it:

enter image description here

Normal MenuItem:

enter image description here

Anyone got any ideas on how to fix this?


Solution

  • What is an item ItemContainerTemplate...

    I think you want to manipulate the MenuItem.ItemContainerStyle instead, otherwise you create two MenuItems as observed.


    The MenuItem.ItemTemplate already defines what is inside the given item container (varies by control, here MenuItem, in a ComboBox it's a ComboBoxItem, etc.). As there does not appear to be an ItemContainerTemplate property on the MenuItem you might only be able to use it that way implementing a selector that returns your template and setting it as ItemContainerTemplateSelector.