Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly bind menu items?

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

like image 470
poco Avatar asked Jun 05 '11 23:06

poco


1 Answers

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>
like image 196
svick Avatar answered Nov 15 '22 22:11

svick