如何从磁盘加载 WindowsFormsControlLibrary UserControl,然后在运行时以编程方式将其添加到 Windows 窗体中的控件列表?
我只想从一个文件名开始。
下面的假代码说明了这一点。明确地说,我不想将它添加到 Visual Studio 工具箱并在设计时使用它。相反,我想在运行时加载它,并将它插入到 Windows 窗体中,除了文件名之外一无所知。
if (File.Exists("SomeUserControl.dll"))
{
// Load SomeUserControl.dll from disk
// Do something to make it a control
// ...
UserControl SomeUserControl = new UserControl();
Controls.Add(SomeUserControl);
}
最佳答案
网上有很多例子和问题here on so .
一个非常简短的例子:
// load your dll
System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom("SomeUserControl.dll");
// to get the right type use namespace.controlname
Type type = assembly.GetType("MyControlLibrary.MyUserCtl");
// create an instance
object instanceOfMyType = Activator.CreateInstance(type);
// do something with Control
Control ctrl = instanceOfMyType as Control;
if (ctrl != null)
{
this.Controls.Add(ctrl);
ctrl.Dock = DockStyle.Bottom;
}
并且不要忘记将其包装在 try/catch 中
关于c# - 从磁盘加载 WindowsFormsControlLibrary DLL,然后添加到控件,C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58417696/