sircodesalot
sircodesalot

Reputation: 11439

How do you read a property from a parent object's DataContext?

If I have a situation like this:

<Parent DataContext="...">
    <Child DataContext="..." />
</Parent>

How can the Child access a property on the Parent's DataContext?

Upvotes: 0

Views: 121

Answers (3)

McGarnagle
McGarnagle

Reputation: 102723

It all depends on how you want to access the property, and where it is targeted. You can access it directly from XAML by using RelativeSource:

<Parent DataContext="{...}">
    <Child DataContext="{...}"
        TargetProperty="{Binding 
            RelativeSource={RelativeSource AncestorType=Parent},
            Path=DataContext.Property}" 
     />
</Parent>

This assumes you have, or can create, a dependency property TargetProperty on Child.

Alternatively, if you want to access a property of the parent's view model from the child's view model, then you might want to consider passing a reference, or an encapsulated reference, or a weak reference, to the child's view model.

Upvotes: 3

Fede
Fede

Reputation: 44028

By using a RelativeSource with FindAncestor Mode:

<Grid>
  <ContentPresenter Content="{Binding SomeProperty}">
     <ContentPresenter.ContentTemplate>
         <DataTemplate>
             <!-- Here, the DataContext is SomeProperty, so you need to use a RelativeSource to reach the Grid's DataContext -->
             <TextBox Text="{Binding DataContext.SomeGridViewModelProperty, RelativeSource={RelativeSource AncestorType=Grid}}"/>
         </DataTemplate>
     </ContentPresenter.ContentTemplate>
  </ContentPresenter>
</Grid>

Upvotes: 2

Jonathan Allen
Jonathan Allen

Reputation: 70277

Assuming the parent object's DC has a property Foo, to read Foo.Bar:

DataContext="{Binding Foo}" Text="{Binding Bar}"

OR

Text="{Binding Foo.Bar}"

Upvotes: 1

Related Questions