如何在运行时将EditorAttribute(Editor)添加到对象的属性?
我有一个名为
我无法更改
我想要做的是在运行时添加
我有一个名为
My.Settings.ExcludeFiles
的属性,由设置设计器创建为 Public Property ExcludedFiles() As Global.System.Collections.Specialized.StringCollection
。当通过属性网格编辑 ExcludedFiles
时,“String Collection Editor”会生成“未找到类型为'System.String'的构造函数”的运行时异常。我无法更改
ExcludeFiles
属性的属性,因为它们将在进行任何设置更改时被覆盖。因此,我必须在运行时附加/添加Editor / EditorAttribute。我想要做的是在运行时添加
StringCollectionEditor
,如下所示为设计时属性。 <Editor(GetType(StringCollectionEditor), GetType(UITypeEditor))> _
Solutions
Method #1
TypeDescriptor.AddAttributes( _
GetType(Specialized.StringCollection), _
New EditorAttribute( _
"System.Windows.Forms.Design.StringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", _
GetType(System.Drawing.Design.UITypeEditor)))
您只需添加此属性一次,例如应用程序初始化。
方法 #2
更加灵活。请参见 Nicolas Cadilhac 在 Adding Editor / EditorAttribute at Run-time (Dynamically) to an Object's Property 中的答案。它使用了派生自 CustomTypeDescriptor 和 TypeDescriptionProvider 类的类。您只需添加提供程序一次,例如应用程序初始化。
TypeDescriptor
检查类型时起作用,而不能通过“真正”的反射实现:例如,Attribute.GetCustomAttributes
不会返回使用TypeDescriptor.AddAttributes
添加的属性。无论如何,在这种情况下,它完全实现了预期的目标,所以+1;) - Thomas Levesque