Visual Studio Design Time Property - Form List

[EDIT] To be clear, I know how to get a list of forms through reflection. I'm more interested in the design-time property grid.

I have a user control with a public property of type Form.
I want to be able to select a form at design time from the drop-down list.
I want to populate a form dropdown from a namespace: UI.Foo.Forms

This will work if you have a public Control property. During development, the property will automatically populate the drop-down list with all the form controls for which you can choose. I just want to fill it with all the forms in the namespace.

How should I do it? I hope I will be clear enough, so there is no confusion. I am looking for code examples, if at all possible. I try not to spend too much time on this when I have other deadlines.

Thanks for your help in advance.

+5
source share
2 answers

You can easily get classes through Reflection:

var formNames = this.GetType().Assembly.GetTypes().Where(x => x.Namespace == "UI.Foo.Forms").Select(x => x.Name);

Assuming you call this from code in the same assembly as your forms, you will get names of all types that are in the "UI.Foo.Forms" namespace. Then you can present this in the drop-down list and, ultimately, create an instance that the user selected again:

Activator.CreateInstance(this.GetType("UI.Form.Forms.FormClassName"));

[] :

Form :

[Browsable(true)]
[Editor(typeof(TestDesignProperty), typeof(UITypeEditor))]
[DefaultValue(null)]
public Type FormType { get; set; }

. , , , , , .

public class TestDesignProperty : UITypeEditor
{
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.DropDown;
    }

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        var edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

        ListBox lb = new ListBox();
        foreach(var type in this.GetType().Assembly.GetTypes())
        {
            lb.Items.Add(type);
        }

        if (value != null)
        {
            lb.SelectedItem = value;
        }

        edSvc.DropDownControl(lb);

        value = (Type)lb.SelectedItem;

        return value;
    }
}
+7

, , :

public class TestDesignProperty : UITypeEditor
{

    // ...

    IWindowsFormsEditorService editorService;

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            // ...
            editorService = edSvc ; // so can be referenced in the click event handler

            ListBox lb = new ListBox();
            lb.Click += new EventHandler(lb_Click);
            // ... 
        }



    void lb_Click(object sender, EventArgs e)
    {
        editorService.CloseDropDown();
    }

}
+2

All Articles