wpf - 从模板绑定(bind)到 View 模型的属性

我为我的 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}}}"

其中 MyContentPropertyNameGameViewModel 中表示按钮内容的属性。

注意:从代码片段来看,两个绑定(bind)似乎会产生相同的结果,将它们都添加到一个示例中,您可以选择要达到的高度以找到正确的上下文。

https://stackoverflow.com/questions/10752448/

相关文章:

sql-server-2008 - 一个选择语句中的不同条件

css - 向右浮动和小时对齐

email - 使用 ssl 的 Yandex smtp 设置

php - 这个 PHP 有什么问题?什么都没有出现

php - 从 php 中的文件夹中读取文件并列出 json 文件中的条目

sql-server - 从数据库中获取高于平均水平的学生

ruby-on-rails - rails : how to check if find_or_in

php - MySQLi 查询以获取表中的最大 id?

asp.net-mvc-2 - 无法将类型 'double?' 隐式转换为 'double'

PHP Google Calendar API - 更新事件