从模板绑定到viewmodel的属性

编程入门 行业动态 更新时间:2024-10-26 20:27:47
本文介绍了从模板绑定到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}}}"

MyContentPropertyName是GameViewModel中的属性,代表按钮的内容.

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的属性

本文发布于:2023-11-14 16:33:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   属性   模板   viewmodel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!