gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:24:50 25 4
gpt4 key购买 nike

如果我创建一个扩展 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 属性和特性声明?

非常感谢。

最佳答案

我发现我可以访问继承类型属性的 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 包装器属性,并覆盖静态构造函数中的元数据以设置新的默认值。

关于c# - 是否可以更改派生类中继承的 DependencyProperty 的 DescriptionAttribute 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9744784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com