Visual Studio Design Time Property - Form List Drop Down

你说的曾经没有我的故事 提交于 2019-11-30 21:45:23

You can easily get the classes via Reflection:

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

Assuming you're calling this from code in the same assembly as your forms, you'll get the names of all the types that are in the "UI.Foo.Forms" namespace. You can then present this in the dropdown and, eventually, instantiate whichever is selected by the user via reflection once more:

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

[Edit] Adding code for the design time stuff:

On your control you can create a Form property as such:

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

Which references the Editor type that must be defined. The code is pretty self-explanatory, with a minimal amount of tweaking, you'll likely be able to get it to produce exactly what you want.

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;
    }
}

The dropdown does not close when item gets selected by clicking it, so this could be useful:

assign the click event handler for the listbox and add the event handler function

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();
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!