我为我的 GameViewModel 创建了一个 View
我有一些这样的xaml
<UserControl.Resources>
<DataTemplate DataType="{x:Type ViewModels:PlayerViewModel}">
<StackPanel>
<Button
Content="{Binding ?????}"
Command="{Binding WrongAnswerCommand}" />
<TextBlock
Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<ListBox Grid.Row="0"
ItemsSource="{Binding Players}"
IsSynchronizedWithCurrentItem="True">
</ListBox>
</Grid>
因此,这是一个可观察的集合 Players。
我需要将按钮内容绑定(bind)到 GameViewModel 的属性。
我应该使用什么?
最佳答案
基本上,您需要上升到更高级别才能获得完整的 View 模型。
有点像
Content="{Binding DataContext.MyContentPropertyName,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ListBox}}}"
或者
Content="{Binding DataContext.MyContentPropertyName,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type UserControl}}}"
其中 MyContentPropertyName
是 GameViewModel
中表示按钮内容的属性。
注意:从代码片段来看,两个绑定(bind)似乎会产生相同的结果,将它们都添加到一个示例中,您可以选择要达到的高度以找到正确的上下文。
https://stackoverflow.com/questions/10752448/