How to correctly bind menu items?
Asked Answered
B

1

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

Bohun answered 5/6, 2011 at 23:50 Comment(0)
D
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>
Dyer answered 6/6, 2011 at 0:21 Comment(3)
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<string>Bohun
@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.Dyer
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 helpBohun

© 2022 - 2024 — McMap. All rights reserved.