您可以通过反射轻松获取类:
var formNames = this.GetType().Assembly.GetTypes().Where(x => x.Namespace == "UI.Foo.Forms").Select(x => x.Name);
假设您从与表单相同的程序集中的代码中调用它,您将获得“UI.Foo.Forms”命名空间中所有类型的名称。然后,您可以在下拉列表中显示它,并最终通过反射再次实例化用户选择的任何一个:
Activator.CreateInstance(this.GetType("UI.Form.Forms.FormClassName"));
[编辑]为设计时的东西添加代码:
在您的控件上,您可以创建一个 Form 属性,如下所示:
[Browsable(true)]
[Editor(typeof(TestDesignProperty), typeof(UITypeEditor))]
[DefaultValue(null)]
public Type FormType { get; set; }
其中引用了必须定义的 Editor 类型。该代码非常不言自明,只需进行少量调整,您就可以让它准确地产生您想要的东西。
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;
}
}