如何在运行时将 EditorAttribute (Editor) 添加到对象的属性?
我有 My.Settings.ExcludeFiles
,由设置设计器创建为 Public Property ExcludedFiles() As Global.System.Collections.Specialized.StringCollection
.编辑时ExcludedFiles
通过属性网格,“字符串集合编辑器”生成“未找到“System.String”类型的构造函数”运行时异常。
我无法更改 ExcludeFiles
的属性属性,因为它们将在下次进行任何设置更改时被覆盖。因此,我必须在运行时附加/添加 Editor/EditorAttribute。
我想要做的是添加 StringCollectionEditor
在运行时,下面显示为设计时属性。
<Editor(GetType(StringCollectionEditor), GetType(UITypeEditor))> _
解决方案
方法#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
更灵活。见尼古拉斯·卡迪拉克
在下面回答 Adding Editor / EditorAttribute at Run-time (Dynamically) to an Object's Property .它使用派生的 CustomTypeDescriptor 和 TypeDescriptionProvider 类。您只需添加一次提供程序,例如应用程序初始化。
最佳答案
在给你我的第一个答案后,我想起了 Marc Gravell 给出的另一个我什至评论的解决方案。信不信由你,你只需要调用 TypeDescriptor.AddAttributes()。
这是在这里:How do I inject a custom UITypeEditor for all properties of a closed-source type? .
对于您的情况,它提供:
TypeDescriptor.AddAttributes(
typeof(StringCollection),
new EditorAttribute("System.Windows.Forms.Design.StringCollectionEditor,
System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
typeof(UITypeEditor)))
因此,也许您应该取消选中我之前的答案并确认此为解决方案(尽管所有功劳都归功于 Marc)。但是当您需要使用 TypeDescriptor 做更复杂的事情时,我之前的文章仍然为您提供了一个很好的技巧。
关于winforms - 在运行时(动态)将 Editor/EditorAttribute 添加到对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2043579/