Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parent's DataContext from a UserControl

I need to access the container's DataContext from a UserControl (a grid containing textboxes and a listbox: I need to insert items in this list box) that I created in WPF: which is the best way to do it?

I was thinking to pass the DataContext as parameter to user control but think there is a cleaner way to do it.

like image 373
Cris Avatar asked Jul 04 '11 19:07

Cris


People also ask

What is UserControl DataContext?

DataContext is inherited to all lower Elements of the XAML and to all the XAML of UserControl s unless it is overwritten somewhere. By setting the UserControl DataContext to itself, this overwrites the DataContext and breaks Inheritance. Instead, nest it one Element deep in the XAML, in your case, the StackPanel .

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.

What is the use of DataContext in WPF?

Every FrameworkElement can be associated with a DataContext which will be used as the default data source during binding, if no other data source is specified in the binding code. Also, the children of this FrameworkElement auotmatically inherit this setting.


1 Answers

Normally the DataContext will be inherited, just do not explicitly set it on the UserControl and it will get it from its parent. If you have to set it you could still use the Parent property to get the parent, which you then can safe-cast to a FrameworkElement and if it is not null you can grab its DataContext.

like image 132
H.B. Avatar answered Oct 03 '22 02:10

H.B.