在运行时(动态)将Editor/EditorAttribute添加到Object的属性

AMi*_*ico 4 propertygrid attributes winforms my.settings

如何在运行时将EditorAttribute(Editor)添加到对象的属性?

我有My.Settings.ExcludeFiles,由设置设计师创建Public Property ExcludedFiles() As Global.System.Collections.Specialized.StringCollection.ExcludedFiles通过属性网格进行编辑时,"字符串集合编辑器"会生成"未找到类型'System.String'上的构造函数"运行时异常.

我无法更改属性的ExcludeFiles属性,因为它们将在下次进行任何设置更改时被覆盖.因此,我必须在运行时附加/添加Editor/EditorAttribute.

我想要做的是添加StringCollectionEditorat运行时,如下所示为design-time属性.

    <Editor(GetType(StringCollectionEditor), GetType(UITypeEditor))> _
Run Code Online (Sandbox Code Playgroud)

解决方案

方法#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)))
Run Code Online (Sandbox Code Playgroud)

您只需添加此属性一次,例如应用程序初始化.

方法#2

更灵活.请参阅下面的Nicolas Cadilhac 在运行时(动态)添加编辑器/ EditorAttribute到对象属性的答案.它使用派生的CustomTypeDescriptor和TypeDescriptionProvider类.您只需添加一次提供程序,例如应用程序初始化.

Nic*_*hac 6

在给出我的第一个答案之后,我想起了Marc Gravell给出的另一个解决方案我甚至评论过.信不信由你,你只需要调用TypeDescriptor.AddAttributes().

这是:如何为闭源类型的所有属性注入自定义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)))
Run Code Online (Sandbox Code Playgroud)

所以也许你应该取消我之前的答案并确认这个解决方案(尽管所有的功劳归功于Marc).但是当你需要使用TypeDescriptor做更复杂的事情时,我之前的帖子仍然给你一个很好的技巧.