Reputation: 1743
I'm trying to bind a DataContext to some element in my resources. The resources are embedded in a ContentControl that is created via a DataTemplate and has already a DataContext set. This DataContext has a StatusController (property name: Status) I want to attach to the StatusControllerViewModel that transforms the properties and events from the StatusController to View conform properties:
<ContentControl.Resources>
<CSharp:StatusControllerViewModel DataContext="{Binding Status}" x:Key="StatusViewModel"/>
</ContentControl.Resources>
The problem is that this message shows up:
Cannot find governing FrameworkElement or FrameworkContentElement for target element
The StatusControllerViewModel is derived from DependencyObject and has a DependencyProperty named DataContext.
When deriving it from Freezable it works, why?
Upvotes: 0
Views: 136
Reputation: 5666
The reason of your problem depends on WPF does not know what FrameworkElement
to use to get the DataContext, because your StatusControllerViewModel
does not belong to the visual or logical tree of the ContentControl (since it is a resource).
If you make the StatusControllerViewModel
derive from Freezable
- as you told - you solve your problem, since Freezable objects can inherit the DataContext even when they are not in the visual or logical tree.
Your can find a full explanation about Freezable DataContext inheritance here:
Normally, [...] DataContext bindings are resolved based on the target dependency object's position within the element tree (or the namescope to which the target dependency object belongs). But in this case, the target dependency object is not actually in the tree. Instead, it is just a property value on another object. That other object may or may not be in the tree.
The reason the Freezable trick works is because a Freezable object has its own notion of “inheritance context”. When the property engine sets the effective value of a dependency property, it looks at that new value to determine whether it is a dependency object that would like to be part of a special inheritance tree.
I hope it can help you.
Upvotes: 1