从模板绑定到ViewModel的属性

los*_*rik 1 wpf xaml binding templates

我为GameViewModel制作了一个视图

我有一些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>
Run Code Online (Sandbox Code Playgroud)

因此,这里是一个可观察的玩家集合。

我需要将按钮内容绑定到GameViewModel的属性。

我应该使用什么?

XAM*_*eLi 5

基本上,您需要更高的级别才能获得完整视图模型。

就像是

Content="{Binding DataContext.MyContentPropertyName, 
                  RelativeSource={RelativeSource FindAncestor, 
                                                 AncestorType={x:Type ListBox}}}"
Run Code Online (Sandbox Code Playgroud)

要么

Content="{Binding DataContext.MyContentPropertyName, 
                  RelativeSource={RelativeSource FindAncestor, 
                                             AncestorType={x:Type UserControl}}}"
Run Code Online (Sandbox Code Playgroud)

MyContentPropertyName该属性在哪里GameViewModel代表按钮的内容。

注意:从片段中可以看出,两个绑定都将产生相同的结果,将它们都添加为一个示例,您可以选择查找想要的上下文的高度。