New Dev
New Dev

Reputation: 49580

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?

Upvotes: 1

Views: 1880

Answers (1)

Abe Heidebrecht
Abe Heidebrecht

Reputation: 30498

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>

Upvotes: 4

Related Questions