John
John

Reputation: 7049

DependencyObject's binding context

I'm trying to understand the low-level details of the Silverlight dependency property system.

I realize that DependencyObject has no explicit DataContext property or even the notion of a parent.

The Behavior class however, which derives from DependencyObject, has bindings use the DataContext of what it is attached to as the Source of the bindings on itself.

My question is: Can I derive a class from DependencyObject and somehow determine which other object to use at the Source for bindings? Or more clearly: How to implement something like the Behavior class?

Upvotes: 2

Views: 1126

Answers (1)

Denis
Denis

Reputation: 4115

DataContext is a FrameworkElement property. By using a form of parent-child property inheritance, the binding system can resolve a DataContext that exists on a parent element, even if the child object (which has the target property) is not a FrameworkElement and therefore does not hold its own DataContext value. However, that parent element must be a FrameworkElement in order to set and hold the DataContext. Alternatively, you must define the binding such that it can function with a null DataContext.

and

Starting with Silverlight 4, the target can also be a DependencyProperty of a DependencyObject in the following cases:

  • The DependencyObject is the value of a property of a FrameworkElement.

  • The DependencyObject is in a collection that is the value of a FrameworkElement property (for example, the Resources property).

  • The DependencyObject is in a DependencyObjectCollection.

Starting with Silverlight 5, the target can also be the Value property of a Setter within a Style. For an example, see the Style class overview.

So the answer to your question is: yes, you can derive your class from DependencyObject and bindings on its dependency properties will work as long as conditions listed above are met or binding does not rely on DataContext (ElementName or Source properties used)

Upvotes: 2

Related Questions