C# 是否可以更改派生类中继承的DependencyProperty的DescriptionAttribute值?
如果我创建了一个扩展C# 是否可以更改派生类中继承的DependencyProperty的DescriptionAttribute值?,c#,wpf,dependency-properties,derived-class,inherited,C#,Wpf,Dependency Properties,Derived Class,Inherited,如果我创建了一个扩展UserControl的类,并希望为UserControl中声明的dependencProperty设置默认值,比如FontSize,我可以添加如下静态构造函数: static MyUserControl() { UserControl.FontSizeProperty.OverrideMetadata(typeof(MyUserControl), new FrameworkPropertyMetadata(28.0)); } 在学习OverrideMetadat
UserControl
的类,并希望为UserControl
中声明的dependencProperty
设置默认值,比如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的属性窗口中。我的问题是,是否可以以类似于重写元数据的方式设置此DependencyProperty
的DescriptionAttribute
值?或者我必须保留CLR getter/setter属性和属性声明吗
非常感谢。我发现我可以访问继承类型属性的
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包装器属性,并覆盖静态构造函数中的元数据以设置新的默认值。您是否确实在询问是否可以在运行时更改当前程序集中的属性值?因为如果是:否,您不能这样做,因为属性与元数据一起存储在程序集中,并且静态地保留在那里。@daveclemer,请不要进行无意义的编辑。将标记交换到是一个无意义的编辑,应该被拒绝。@Sheridan,首先这是很久以前做的,其次这是标记清理工作的一部分,以减少重复标记并改进搜索,第三,通过将标记更改回dependency属性,您再次创建了重复标记(有人可能会再次删除),最后您在实际使用的dependency properties标记中降低了分数。