从模板绑定到viewmodel的属性 [英] Binding to viewmodel's property from a template

查看:99
本文介绍了从模板绑定到viewmodel的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为GameViewModel制作了一个视图

I made a view for my 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>

所以,这里是一个可观察的玩家集合.

So, here it is an observable collection Players.

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

I need the button content to be binded to GameViewModel's property.

我应该使用什么?

推荐答案

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

Basically, you need to go up to a higher level to get the full view model.

类似

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

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

MyContentPropertyNameGameViewModel中的属性,代表按钮的内容.

Where MyContentPropertyName is the property in GameViewModel that represents the content of the button.

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

Note: from the snippet it seems that both bindings will produce the same result, adding them both to make an example that you can choose how high you want to go to find the right context.

这篇关于从模板绑定到viewmodel的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆