4

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?

1 Answer 1

9

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.

1
  • I assume that adding UseItemContainerTemplate only applies when you have subitems, right?
    – Ole K
    Commented Apr 22, 2016 at 8:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.