Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 527
Inferis Avatar asked Mar 10 '09 15:03

Inferis


People also ask

How does DataContext work WPF?

User interface elements in WPF have a DataContext dependency property. That property has the aforementioned "value inheritance" feature enabled, so if you set the DataContext on an element to a Student object, the DataContext property on all of its logical descendant elements will reference that Student object too.

What is DataContext in MVVM?

DataContext is the head of everything. It makes sure that your View is hooked up with ViewModel. There are 3 ways to hook-up View with ViewModel. Within XAML. Code-Behind.

What is the DataContext?

The DataContext is the source of all entities mapped over a database connection. It tracks changes that you made to all retrieved entities and maintains an "identity cache" that guarantees that entities retrieved more than one time are represented by using the same object instance.


2 Answers

Maybe try

Window Name="TheWindow"
...
ListBox.ItemsSource = {Binding DataContext.Supports, ElementName=TheWindow}
like image 187
user76035 Avatar answered Sep 19 '22 19:09

user76035


Another little trick to bind to your root context

<ListBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}, AncestorLevel=1}, Path=DataContext.Supports}"/>
like image 23
TonyT_32909023190 Avatar answered Sep 18 '22 19:09

TonyT_32909023190