8

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

svick
  • 236,525
  • 50
  • 385
  • 514
poco
  • 2,935
  • 6
  • 37
  • 54

1 Answers1

16

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>
svick
  • 236,525
  • 50
  • 385
  • 514
  • One step closer sir. I am firing off the command now, however When the list o ToonNames is not being populated... however the it looks as though it is creating the space for the proper number of names.. just no header info. May help to tell you that ToonNames is ObservableCollection – poco Jun 06 '11 at 00:38
  • 1
    @poco, you should have said so at the beginning, I don't have a crystal ball to know how your code looks. See updated answer. – svick Jun 06 '11 at 02:03
  • 5
    crystal balls are very helpful sir, you should look into them! I haven't had a chance to test your latest code but was able to get it working from your first edit, thanks for your help – poco Jun 06 '11 at 15:09