Templating MahApps.Metro DropDownButton menu items
When displaying a MahApps.Metro DropDownButton, it’s often easy to set a DisplayMemberPath, but what happens if you want something more complicated in your menu items than just the member text?
I tried a few things, which didn’t work:
- Setting the ItemTemplate naively will also break the main label of the DropDownButton.
- Putting DataTemplates inside the DropDownButton.Resources tag didn’t seem to get picked up.
- Setting the template from the item container style worked, but broke the MenuItem template, causing a lot of ugly XAML duplication from the default WPF MenuItem to make it look consistent
What finally did work was setting the ItemTemplate to a ContentPresenter, whose Resources section then decided which template to use:
<Metro:DropDownButton.ItemTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding}">
<ContentPresenter.Resources>
<DataTemplate DataType="{x:Type ViewModels:MyViewModel}">
<!-- Insert your custom template here, icons, etc. -->
</DataTemplate>
<DataTemplate DataType="{x:Type System:String}">
<!-- Template for the default item on the button (i.e. the button content before
opening the menu) -->
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
</DataTemplate>
</Metro:DropDownButton.ItemTemplate>
This trick may also work with ContextMenu but I haven’t tried it.