如果我创建了一个扩展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属性和属性声明?
非常感谢提前。
答案 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
然后我发现您无法在运行时从这些文章中更改声明的属性值:
因此,我将继续使用新的DescriptionAttribute
值声明CLR包装器属性,并覆盖静态构造函数中的元数据,只是为了设置新的默认值。