2

I made a view for my GameViewModel

I have some xaml like that

<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.

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

What should I use?

loshurik
  • 95
  • 2
  • 9

1 Answers1

8

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

Something like

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

Or

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

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.

XAMeLi
  • 6,189
  • 2
  • 22
  • 29