【问题标题】:Is it possible to change the DescriptionAttribute value of an inherited DependencyProperty in a derived class?是否可以更改派生类中继承的 DependencyProperty 的 DescriptionAttribute 值?
【发布时间】:2012-03-16 21:33:14
【问题描述】:

如果我创建一个扩展 UserControl 的类,并希望为在 UserControl 中声明的 DependencyProperty 设置默认值,例如 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 的属性窗口中显示为弹出工具提示。我的问题是,是否可以以类似于覆盖元数据的方式设置此 DependencyPropertyDescriptionAttribute 值?还是我必须保留 CLR getter/setter 属性和属性声明?

非常感谢。

【问题讨论】:

  • 您实际上是在问是否可以在运行时更改当前程序集中的属性值?因为如果是这样:不,您不能这样做,因为属性与元数据一起存储在程序集中并静态地保留在那里。
  • @DaveClemmer,请不要进行无意义的编辑。将dependency-property 标签替换为dependency-properties 是毫无意义的编辑,应该被拒绝。
  • @Sheridan,首先这是很久以前完成的,其次这是标签清理工作的一部分,以减少重复标签和改进搜索,第三是将标签改回依赖属性,您再次创建了一个重复的标签(有人可能会再次删除),最后您在实际使用的依赖属性标签中降低了分数。

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


【解决方案1】:

我发现我可以访问继承类型属性的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

因此,我将继续使用新的 DescriptionAttribute 值声明 CLR 包装器属性,并覆盖静态构造函数中的元数据,以设置新的默认值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    相关资源
    最近更新 更多