How to: Add an Owner Type for a Dependency Property

This example shows how to add a class as an owner of a dependency property registered for a different type. By doing this, the WPF XAML reader and property system are both able to recognize the class as an additional owner of the property. Adding as owner optionally allows the adding class to provide type-specific metadata.

In the following example, StateProperty is a property registered by the MyStateControl class. The class UnrelatedStateControl adds itself as an owner of the StateProperty using the AddOwner method, specifically using the signature that allows for new metadata for the dependency property as it exists on the adding type. Notice that you should provide common language runtime (CLR) accessors for the property similar to the example shown in the How to: Implement a Dependency Property example, as well as re-expose the dependency property identifier on the class being added as owner.

Without wrappers, the dependency property would still work from the perspective of programmatic access using GetValue or SetValue. But you typically want to parallel this property-system behavior with the CLR property wrappers. The wrappers make it easier to set the dependency property programatically, and make it possible to set the properties as XAML attributes.

To find out how to override default metadata, see How to: Override Metadata for a Dependency Property.

Example

public class MyStateControl : ButtonBase
{
  public MyStateControl() : base() { }
  public Boolean State
  {
    get { return (Boolean)this.GetValue(StateProperty); }
    set { this.SetValue(StateProperty, value); } 
  }
  public static readonly DependencyProperty StateProperty = DependencyProperty.Register(
    "State", typeof(Boolean), typeof(MyStateControl),new PropertyMetadata(false));
}

  ...

public class UnrelatedStateControl : Control
{
  public UnrelatedStateControl() { }
  public static readonly DependencyProperty StateProperty = MyStateControl.StateProperty.AddOwner(typeof(UnrelatedStateControl), new PropertyMetadata(true));
  public Boolean State
  {
    get { return (Boolean)this.GetValue(StateProperty); }
    set { this.SetValue(StateProperty, value); }
  }
}

See Also

Concepts

Custom Dependency Properties
Dependency Properties Overview