在我的ListBox ItemTemplate中,绑定到我的命令有问题。我的命令是在我的ViewModel中定义的,但是因为我使用ItemsSource作为我的列表框,所以它被设置为DataContext。
<ListBox ItemsSource="{Binding CreatureModel.TypeFlagsValues}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding}" Command="{Binding SetCommand">
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>我试过用RelativeSource
Command="{Binding SetCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vm:CreatureEditorViewModel}}}"和
<DataTemplate DataType="vm:CreatureEditorViewModel">
<CheckBox Content="{Binding}" Command="{Binding SetCommand}" CommandParameter="test">
</CheckBox>
</DataTemplate>我觉得我错过了一些简单的东西。
发布于 2015-09-23 21:45:45
你几乎把RelativeSource做得很好。
试试这个:
Command="{Binding Path=DataContext.SetCommand,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ItemsControl}} }"或者,您可以为列表框指定名称(例如"_listBox“),并使用以下绑定:
Command="{Binding DataContext.SetCommand, ElementName=_listBox}发布于 2015-09-23 21:43:14
尝试在命令上设置ElementName和路径;您必须在ListBox上设置x:Name,然后可以引用父DataContext。
<ListBox x:Name="list" ItemsSource="{Binding CreatureModel.TypeFlagsValues}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding}" Command="{Binding ElementName=list,
Path=DataContext.SetCommand}">
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>https://stackoverflow.com/questions/32749650
复制相似问题