问题描述
如何在运行时EditorAttribute(编辑)添加到对象的属性?
我 My.Settings.ExcludeFiles
,这是由设计师设置创建为公共财产ExcludedFiles()由于Global.System.Collections。 Specialized.StringCollection
。当编辑 ExcludedFiles
通过属性网格,字符串集合编辑器,关于类型构造'System.String'找不到生成运行时异常。
I have My.Settings.ExcludeFiles
, which is created by the settings designer as Public Property ExcludedFiles() As Global.System.Collections.Specialized.StringCollection
. When editing ExcludedFiles
via a property grid, the "String Collection Editor" generates a "Constructor on type 'System.String' not found" run-time exception.
我不能更改 ExcludeFiles
属性的特性,因为他们将在未来任何时间设置更改时被覆盖。因此,我必须附上/添加编辑/ EditorAttribute在运行时。
I cannot change the attributes of the ExcludeFiles
property because they will be overwritten the next time any setting changes are made. Therefore, I must attach/add the Editor/EditorAttribute at run-time.
我想要做的就是添加 StringCollectionEditor
在运行时,如下图所示的设计时属性。
What I want to do is add the StringCollectionEditor
at run-time, shown below as design-time attribute.
<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)))
您只需一次添加此属性,如应用程序初始化。
You only have to add this attribute once, such as application initialization.
更灵活。见萨科Cadilhac
下面回答在http://stackoverflow.com/questions/2043579/adding-editor-editorattribute-at-run-time-dynamically-to-an-objects-property/2044673#2044673.它采用衍生CustomTypeDescriptor和TypeDescriptionProvider类。你只需要添加一次提供商,如应用程序的初始化。
More flexible. See Nicolas Cadilhacanswer below at http://stackoverflow.com/questions/2043579/adding-editor-editorattribute-at-run-time-dynamically-to-an-objects-property/2044673#2044673. It uses derived CustomTypeDescriptor and TypeDescriptionProvider classes. You only have to add the provider once, such as application initialization.
推荐答案
给你我的第一个答案之后,我想起马克·Gravell给出另一种解决方案,我连评论。信不信由你,你只需要调用TypeDescriptor.AddAttributes()。
After giving you my first answer, I remembered another solution given by Marc Gravell that I even commented. Believe it or not, you just need to call TypeDescriptor.AddAttributes().
这是在这里:How我做了注入闭源类型的所有属性的自定义UITypeEditor的?。
有关你的情况给出了:
TypeDescriptor.AddAttributes(
typeof(StringCollection),
new EditorAttribute("System.Windows.Forms.Design.StringCollectionEditor,
System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
typeof(UITypeEditor)))
因此,也许你应该取消我的previous答案,并确认这个作为解决方案(尽管所有归功于马克)。但是,当你需要用一个TypeDescriptor做多复杂的东西我的previous后仍然给你一个很好的技术。
So maybe you should uncheck my previous answer and confirm this one as the solution (although all the credit goes to Marc). But my previous post still gives you a good technique when you need to do more complex stuff with a TypeDescriptor.
这篇关于添加编辑/ EditorAttribute在运行时(动态)为对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!