简体   繁体   English

如何从父对象的DataContext中读取属性?

[英]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? 子级如何访问父级DataContext上的属性?

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 : 您可以使用RelativeSource 从XAML直接访问它:

<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 . 这假定您在Child上具有或可以创建依赖项属性TargetProperty

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. 或者,如果要从子视图模型访问父视图模型的属性,则可能要考虑将引用,封装引用或弱引用传递给子视图模型。

By using a RelativeSource with FindAncestor Mode: 通过在FindAncestor模式下使用RelativeSource

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

Assuming the parent object's DC has a property Foo, to read Foo.Bar: 假设父对象的DC具有属性Foo,以读取Foo.Bar:

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

OR 要么

Text="{Binding Foo.Bar}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM