Inferis
Inferis

Reputation: 4662

How can I access the root DataContext in a DataTemplate in WPF?

I have a grid of items which is populated using databinding. In the grid I have a DataTemplate for certain cells. I need to access the DataContext of the root element (the one which is hosting the grid) so that I can access additional bindings to support my datatemplate.

So you have:

Window
    Window.DataContext = TheDataSourceWithItemsAndSupports
    DataGrid.ItemsSource = {Binding Items}
        DataTemplate
            ListBox.ItemsSource = {Binding Supports}

I want the {Binding Supports} on TheDataSourceWithItemsAndSupports, but I don't see how to do that. I tried specifying {Binding} but that always returns null. I also tried using RelativeSource FindAncestor, but that yields null too.

Any clues?

Upvotes: 11

Views: 10986

Answers (4)

TonyT_32909023190
TonyT_32909023190

Reputation: 786

Another little trick to bind to your root context

<ListBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}, AncestorLevel=1}, Path=DataContext.Supports}"/>

Upvotes: 4

Ivan I
Ivan I

Reputation: 9990

My solution was to expose whole DataContext class by implementing This field

get
{
    return this;
}

and then binding to it.

Upvotes: 1

Sergey Aldoukhov
Sergey Aldoukhov

Reputation: 22744

It should work the way you describe. Only thing I see your DataTemplate is not ItemTemplate. You should also look at the output window to see where bindings fail.

Upvotes: 0

user76035
user76035

Reputation: 1536

Maybe try

Window Name="TheWindow"
...
ListBox.ItemsSource = {Binding DataContext.Supports, ElementName=TheWindow}

Upvotes: 19

Related Questions