Adding Editor / EditorAttribute at Run-time (Dynamically) to an Object's Property

attributes, my.settings, propertygrid, winforms

Solution

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().

This is here: How do I inject a custom UITypeEditor for all properties of a closed-source type?.

For your case it gives:

TypeDescriptor.AddAttributes(
    typeof(StringCollection),
    new EditorAttribute("System.Windows.Forms.Design.StringCollectionEditor,
        System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
        typeof(UITypeEditor)))

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.

Problem

How to add the EditorAttribute (Editor) to an object's property at run-time? 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. 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. What I want to do is add the `StringCollectionEditor` at run-time, shown below as design-time attribute. ``` <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))) ``` You only have to add this attribute once, such as application initialization. Method #2 More flexible. See Nicolas Cadilhac answer below at Adding Editor / EditorAttribute at Run-time (Dynamically) to an Object's Property. It uses derived CustomTypeDescriptor and TypeDescriptionProvider classes. You only have to add the provider once, such as application initialization.

Original source

Related problems