【发布时间】: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 的属性窗口中显示为弹出工具提示。我的问题是,是否可以以类似于覆盖元数据的方式设置此 DependencyProperty 的 DescriptionAttribute 值?还是我必须保留 CLR getter/setter 属性和属性声明?
非常感谢。
【问题讨论】:
-
您实际上是在问是否可以在运行时更改当前程序集中的属性值?因为如果是这样:不,您不能这样做,因为属性与元数据一起存储在程序集中并静态地保留在那里。
-
@DaveClemmer,请不要进行无意义的编辑。将dependency-property 标签替换为dependency-properties 是毫无意义的编辑,应该被拒绝。
-
@Sheridan,首先这是很久以前完成的,其次这是标签清理工作的一部分,以减少重复标签和改进搜索,第三是将标签改回依赖属性,您再次创建了一个重复的标签(有人可能会再次删除),最后您在实际使用的依赖属性标签中降低了分数。
标签: c# wpf dependency-properties derived-class inherited