Robert Hegner
Robert Hegner

Reputation: 9376

UserControl with property of type Type

I'm implementing a UserControl with a property of type Type.

public partial class MyUserControl: UserControl
{
    public MyUserControl()
    {
        InitializeComponent();
    }

    public Type PluginType { get; set; } = typeof(IPlugin);
}

When placing MyUserControl on a form I can see the PluginType property in the designer, but I cannot edit it.

How can I make this property editable? Ideally the designer would show an editor where I can pick one of the types in my assembly (or any assembly). Is there such an editor?

Upvotes: 2

Views: 919

Answers (1)

cdel
cdel

Reputation: 706

Use Editor attribute telling wich class will be used for editing of property:

[Editor("Mynamespace.TypeSelector , System.Design", typeof(UITypeEditor)), Localizable(true)]
public Type PluginType { get; set; }

Define a TypeSelector class:

public class TypeSelector : UITypeEditor
{
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        if (context == null || context.Instance == null)
            return base.GetEditStyle(context);

        return UITypeEditorEditStyle.Modal;
    }
    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        IWindowsFormsEditorService editorService;

        if (context == null || context.Instance == null || provider == null)
            return value;

        editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

        FormTypeSelector dlg = new FormTypeSelector();
        dlg.Value = value;
        dlg.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        if (editorService.ShowDialog(dlg) == System.Windows.Forms.DialogResult.OK)
        {
            return dlg.Value;
        }
        return value;
    }
}

Only thing remaining is to implement FormTypeSelector in which you can select a type and assign it to Value property. Here you can use reflection to filter the types in an assembly wich implements IPlugin.

Upvotes: 2

Related Questions