2011-06-05 61 views
8

如何正确绑定动态创建的菜单项列表。我已经尝试了几件事,但似乎没有任何工作。我得到正确的名称列表,但是我的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> 

命令参数需要一个字符串..不知道如果这是...希望这是一些简单的我只是俯瞰

回答

16

此代码的工作对我来说:

<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> 
+0

一步更近的先生。我现在正在发布命令,但是当列表o ToonNames没有被填充时...但是它看起来好像是为正确的名称创建空间..只是没有标题信息。可能有助于告诉你,ToonNames是ObservableCollection poco 2011-06-06 00:38:23

+0

@poco,你应该在开始时这么说,我没有一个水晶球来知道你的代码的外观。查看更新的答案。 – svick 2011-06-06 02:03:27

+5

水晶球是非常有用的先生,你应该看看他们!我没有机会测试你的最新代码,但能够从你的第一次编辑中得到它,感谢你的帮助 – poco 2011-06-06 15:09:21

相关问题