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?
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.
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.
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.
Maybe try
Window Name="TheWindow"
...
ListBox.ItemsSource = {Binding DataContext.Supports, ElementName=TheWindow}
Another little trick to bind to your root context
<ListBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}, AncestorLevel=1}, Path=DataContext.Supports}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With