我为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的属性
发布评论