C#winforms在运行时实例化未知(在设计时)表单(后期绑定?)
本文关键字:表单 绑定 实例化 运行时 未知 C#winforms | 更新日期: 2023-09-27 18:29:32
我需要在运行时实例化一个包含窗体的dll实例。目前,我有一份关于75多个病例的长切换声明,并且增长迅速。随着这一切的发展,我们还开发了一个列表,其中包含动态调用表单的所有信息
样本案例现在
...
case "state"
State state = new State();
state.Parent = this.Parent;
state.ScreenNameLong = "State ";
state.ScreenTitle = "St11 - State";
state.SetupForm();
this.OpenForm(state, state.ScreenTitle);
break;
...
所有需要的信息现在都包含在一个名为menuItem的列表元素中,该元素已被选中。它有form("State")、ScreenNameLong、ScreenTitle等。所有要调用的表单都有Parent对象和SetupForm()方法。
所有dll都在"using"语句和项目引用中引用。似乎我应该能够以某种方式做类似的事情,一次:
Form formToLaunch = (menuItem.form);
formToLaunch.Parent = this.Parent;
formToLaunch.ScreenNameLong = menuItem.descr;
formToLaunch.ScreenTitle = menuItem.scrNumber + " " + formToLaunch.ScreenNameLong;
formToLaunch.SetupForm();
this.OpenForm(formToLaunch, formToLaunch.ScreenNameLong );
我的头撞到墙上了,没有找到一个好的解决办法。我已经研究过使用反射和接口,但它们似乎不符合要求,或者我只是不明白…
所有表单都需要实现一个定义通用成员的接口,例如:
interface IForm : IDisposable
{
Form Parent { get; set; }
string ScreenNameLong { get; set; }
string ScreenTitle { get; set; }
void SetupForm();
}
根据dbc下面的注释,这里IForm
继承自IDisposable
。
从typename中获取Type(可能在您的menuItem.form
中)。你可能需要玩这个:
var type = Type.GetType("form_namespace." + menuItem.form + ", form_assembly_name");
实例化类型,转换为您的接口,并用它做任何您想做的事情:
var formToLaunch = Activator.CreateInstance(type) as IForm;
if (formToLaunch != null)
{
formToLaunch.Parent = this.Parent;
formToLaunch.ScreenNameLong = menuItem.descr;
formToLaunch.ScreenTitle = menuItem.scrNumber + " " + formToLaunch.ScreenNameLong;
formToLaunch.SetupForm();
this.OpenForm(formToLaunch, formToLaunch.ScreenNameLong);
}