如何使用反射在 WPF 中加载 UserControl? [英] How to load a UserControl in WPF with reflection?
问题描述
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var assm = Assembly.LoadFrom("wpflib.dll");
foreach (var t in assm.GetTypes())
{
var i = t.GetInterface("test.ILib");
if (i != null)
{
var tmp = Activator.CreateInstance(typeof(UserControl)) as UserControl;
this.stackPanel1.Children.Add(tmp);
}
}
}
tmp(wpflib.dll 中的 UserControl1)只包含一个标签和一个文本框.
tmp(UserControl1 in wpflib.dll) only contains a label and a textbox.
Windows1 (test.exe) 引用 ILib.dll,并且只包含一个 stackPanel1.
Windows1 (test.exe) reference ILib.dll, and only contains a stackPanel1.
但是,为什么 Windows1(stackPanel1) 中没有 nohong?
But, why there is nothong in Windows1(stackPanel1)?
推荐答案
您根本没有从 DLL 实例化类型.而不是:
You are not instantiating the type from the DLL at all. Instead of:
var tmp = Activator.CreateInstance(typeof(UserControl)) as UserControl;
写:
var tmp = Activator.CreateInstance(t) as UserControl;
此外,我建议您实际编写
Furthermore, I would recommend that you actually write
var tmp = (UserControl) Activator.CreateInstance(t);
相反.否则,如果您有错误,稍后您将收到空引用异常,这不是非常有用且难以调试.通过这种方式,您可以在错误实际发生的正确位置获得更有意义的类型转换异常.
instead. Otherwise, if you have a bug, you will get a null-reference exception later on, which is not very informative and hard to debug. This way you get a more meaningful type-cast exception in the right place where the bug actually happens.
这篇关于如何使用反射在 WPF 中加载 UserControl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!