Search code examples
c#wpfdependency-propertiesderived-classinherited

Is it possible to change the DescriptionAttribute value of an inherited DependencyProperty in a derived class?


If I create a class that extends UserControl and want to set a default value for a DependencyProperty that is declared in UserControl, say FontSize, I can add a static constructor like the following:

static MyUserControl()
{
    UserControl.FontSizeProperty.OverrideMetadata(typeof(MyUserControl), 
new FrameworkPropertyMetadata(28.0));
}

Before I learned about the OverrideMetadata method, I used to override the property and set the DescriptionAttribute in the following way:

public new static readonly DependencyProperty FontSizeProperty = 
DependencyProperty.Register("FontSize", typeof(double), typeof(MyUserControl), 
new PropertyMetadata(28.0));

[Description("My custom description."), Category("Text")]
public new double FontSize
{
    get { return (double)GetValue(FontSizeProperty); }
    set { SetValue(FontSizeProperty, value); }
}

The DescriptionAttribute value is displayed as a popup tooltip in the Properties Window of Visual Studio when a user moves the mouse pointer over the relevant property name. My question is, is it possible to set the DescriptionAttribute value of this DependencyProperty in a similar way to overriding the metadata? Or will I have to keep the CLR getter/setter property and attribute declaration?

Many thanks in advance.


Solution

  • I found that I could access the DescriptionAttribute value of the inherited type property, but only from an instance constructor and not the static constuctor because I needed a reference to the control object. Also, I could not set it using this method as it was a read only property:

    AttributeCollection attributes = 
        TypeDescriptor.GetProperties(this)["FontSize"].Attributes;
    DescriptionAttribute attribute = 
        (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];
    attribute.Description = "Custom description"; // not possible - read only property
    

    I then discovered that you can't change declared attribute values at run time from these articles:

    1. Can attributes be added dynamically in C#?
    2. Programmatically add an attribute to a method or parameter

    I will therefore continue to declare the CLR wrapper properties with new DescriptionAttribute values and override the metadata in the static constructor just to set new default values.