【问题标题】:Binding to viewmodel's property from a template从模板绑定到视图模型的属性
【发布时间】:2012-05-25 10:07:25
【问题描述】:

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

所以,这里是一个可观察的 Players 集合。

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

我应该使用什么?

【问题讨论】:

    标签: wpf templates xaml binding


    【解决方案1】:

    基本上,你需要更上一层楼才能获得完整的视图模型。

    类似

    Content="{Binding DataContext.MyContentPropertyName, 
                      RelativeSource={RelativeSource FindAncestor, 
                                                     AncestorType={x:Type ListBox}}}"
    

    或者

    Content="{Binding DataContext.MyContentPropertyName, 
                      RelativeSource={RelativeSource FindAncestor, 
                                                 AncestorType={x:Type UserControl}}}"
    

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

    注意:从 sn-p 看来,这两个绑定会产生相同的结果,将它们都添加以作为示例,您可以选择要查找正确上下文的高度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 2020-07-20
      • 2013-03-22
      • 2023-03-20
      相关资源
      最近更新 更多