是否可以在派生类中更改继承的DependencyProperty的DescriptionAttribute值?

时间:2012-03-16 21:33:14

标签: c# wpf dependency-properties derived-class inherited

如果我创建了一个扩展UserControl并希望为DependencyProperty中声明的UserControl设置默认值的类,比如FontSize,我可以添加一个静态构造函数如下:

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

在我了解OverrideMetadata方法之前,我曾使用以下方式覆盖属性并设置DescriptionAttribute

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); }
}

当用户将鼠标指针移动到相关属性名称上时,DescriptionAttribute值将在Visual Studio的“属性”窗口中显示为弹出工具提示。我的问题是,是否可以以类似于覆盖元数据的方式设置此DescriptionAttribute的{​​{1}}值?或者我是否必须保留CLR getter / setter属性和属性声明?

非常感谢提前。

1 个答案:

答案 0 :(得分:2)

我发现我可以访问继承的type属性的DescriptionAttribute值,但只能访问实例构造函数而不是静态构造函数,因为我需要对控件对象的引用。此外,我无法使用此方法设置它,因为它是只读属性:

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

然后我发现您无法在运行时从这些文章中更改声明的属性值:

  1. Can attributes be added dynamically in C#?
  2. Programmatically add an attribute to a method or parameter
  3. 因此,我将继续使用新的DescriptionAttribute值声明CLR包装器属性,并覆盖静态构造函数中的元数据,只是为了设置新的默认值。