Search code examples
wpfdependency-propertiesattached-properties

Dependency Properties - How to add an owner so it acts as an attached property?


Basically, is there any way to add an owner to a DependenyProperty so that it becomes an attached property of that new owner? That way I can do something like:

PrimaryControl - Original Owner
OtherControl - 2nd owner

<my:Something my:OtherControl.MyProperty="hello world" />

Solution

  • Yes, you can do this using AddOwner. Your other control would look like:

    public static class OtherControl {
    
        // MyProperty attached property
        public static readonly DependencyProperty MyPropertyProperty =
            PrimaryControl.MyPropertyProperty.AddOwner(typeof(OtherControl));
    
        public static string GetMyProperty(DependencyObject obj) {
            return (string)obj.GetValue(MyPropertyProperty);
        }
    
        public static void SetMyProperty(DependencyObject obj, string value) {
            obj.SetValue(MyPropertyProperty, value);
        }
    
    }