简体   繁体   中英

Binding to the DataContext of the Item in the ItemsControl

How can I bind to the Item's DataContext in the ItemsControl from within a nested data template (a data template of a control within the item's data template)?

I can't use TemplatedParent , because it's double templated. And I can't figure out how to use FindAncestor,AncestorType because I don't know what the type is for each Item.

Any idea?

If I'm reading this correctly, you have:

- ItemsControl
  |- ItemTemplate                    Item.DataContext<--|
     |- Button                                          | 
        |- ContentTemplate <-- Bind something in this to|

If that is the case, what you're looking for is ContentPresenter . That is the type of container that ItemsControl generates. The problem is that you're going to have multiple ContentPresenter ancestors. You can do handle this with the AncestorLevel property of the RelativeSource .

So, in my example, the DataTemplate of the Button can access the DataContext of the row by:

<DataTemplate>
    <TextBlock Text="{Binding DataContext.Name, RelativeSource={RelativeSource AncestorType={x:Type ContentPresenter}, AncestorLevel=2}}" />
</DataTemplate>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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