How to access parent's DataContext from a UserControl

Cris picture Cris · Jul 4, 2011 · Viewed 24.8k times · Source

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.

Answer

H.B. picture H.B. · Jul 4, 2011

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.