Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are ItemContainerTemplates used when populating a menu?

I recently spent far too long trying to figure out how to use the ItemContainerTemplate and the UsesItemContainerTemplate property on a menu.

Basically my problem was that no matter what I did, it seemed, it did not pick up on the templates.

<Menu Grid.Row="1" ItemsSource="{Binding MenuItems}" UsesItemContainerTemplate="True">
    <Menu.Resources>
        <ItemContainerTemplate DataType="{x:Type vm:SeparatorViewModel}">
            <Separator />
        </ItemContainerTemplate>
        <ItemContainerTemplate  DataType="{x:Type vm:ActionItemViewModel}">
            <MenuItem Header="{Binding Path=Caption}" ItemsSource="{Binding SubItems}" />
        </ItemContainerTemplate>
    </Menu.Resources>
</Menu>

It would just use MenuItem as the container always.

But why?

like image 780
Thomas Scheelhardt Avatar asked Jan 12 '23 21:01

Thomas Scheelhardt


1 Answers

The solution of course is painfully simple. The MenuItem template must also have its UsesItemContainerTemplate property set to true.

<Menu Grid.Row="1" ItemsSource="{Binding MenuItems}" UsesItemContainerTemplate="True">
    <Menu.Resources>
        <ItemContainerTemplate DataType="{x:Type vm:SeparatorViewModel}">
            <Separator />
        </ItemContainerTemplate>
        <ItemContainerTemplate  DataType="{x:Type vm:ActionItemViewModel}">
            <MenuItem **UsesItemContainerTemplate="True"** Header="{Binding Path=Caption}" ItemsSource="{Binding SubItems}" />
        </ItemContainerTemplate>
    </Menu.Resources>
</Menu>

I hope this can save others from spending time pulling at their possibly already receding hairline.

By the way I was unable to tag this properly with 'ItemContainerTemplate' and 'UsesItemContainerTemplate' since my reputation apparently is too low, so if anyone can do that, that would be great.

Adios.

like image 198
Thomas Scheelhardt Avatar answered Jan 26 '23 01:01

Thomas Scheelhardt