How to correctly bind menu items?

poco picture poco · Jun 6, 2011 · Viewed 13.3k times · Source

How do i correctly bind a dynamical created list of menu items. I have tried several thing but none seem to work. I get the proper list of names, however my ViewSwitchCommand does not seem to fire correctly.

<MenuItem Foreground="White" Header="Names" ItemsSource="{Binding Player.ToonNames}" Command="{Binding ViewSwitchCommand}" CommandParameter="{Binding Header}"/>

However if i don't do it dynamically and do it like this then everything works just fine can get it to work

<MenuItem Foreground="White" Header="Names">
<MenuItem Foreground="Black" Header="Chat" Command="{Binding ViewSwitchCommand}"     CommandParameter="player1" />
<MenuItem Foreground="Black" Header="Craft" Command="{Binding ViewSwitchCommand}" CommandParameter="player2" />
</MenuItem>

The command parameter expects a string.. not sure if that is it... hopefully this is something simple i'm just overlooking

Answer

svick picture svick · Jun 6, 2011

This code works for me:

<MenuItem Header="Names" ItemsSource="{Binding Player.ToonNames}">
    <MenuItem.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Command" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MenuItem}, Path=DataContext.ViewSwitchCommand}" />
            <Setter Property="CommandParameter" Value="{Binding}" />
        </Style>
    </MenuItem.ItemContainerStyle>
</MenuItem>