如何正确绑定(bind)动态创建的菜单项列表。我尝试了几件事,但似乎都不起作用。我得到了正确的名称列表,但是我的 ViewSwitchCommand 似乎没有正确触发。
<MenuItem Foreground="White" Header="Names" ItemsSource="{Binding Player.ToonNames}" Command="{Binding ViewSwitchCommand}" CommandParameter="{Binding Header}"/>
但是,如果我不动态地执行此操作并像这样执行操作,那么一切都会正常工作,可以使其正常工作
<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>
命令参数需要一个字符串..不确定是否是这样...希望这是我刚刚忽略的简单内容
最佳答案
这段代码对我有用:
<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>
关于wpf - 如何正确绑定(bind)菜单项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6246718/