MahApps.Metro DropDownButton command bindings gotcha
When building a DropDownButton that binds to a command on a parent viewmodel rather than one on the actual items of the DropDownButton, it’s important to remember how the DropDownButton’s menu is constructed.
Similarly to WPF ContextMenu
, ToolTip
and Popup
, the contents of the DropDownButton are rendered in a separate visual tree. This means that direct bindings back to the parent viewmodel using ElementName
or AncestorType=DropDownButton
will not work.
Instead, you must reference the ContextMenu above the menu item and use its PlacementTarget
property to get the DropDownButton
that holds the parent view model.
Here is an example:
<mah:DropDownButton ItemsSource="{Binding Path=People}" Content="Say Hello to...">
<mah:DropDownButton.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command"
Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.DataContext.SayHelloCommand}"/>
<Setter Property="CommandParameter" Value="{Binding}"/>
</Style>
</mah:DropDownButton.ItemContainerStyle>
</mah:DropDownButton>