How to correctly bind menu items?

时光怂恿深爱的人放手 提交于 2019-11-29 19:30:26

问题


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


回答1:


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>


来源:https://stackoverflow.com/questions/6246718/how-to-correctly-bind-menu-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!