How to load a UserControl in WPF with reflection?

夙愿已清 提交于 2019-12-30 07:33:13

问题


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(UserControl1 in wpflib.dll) only contains a label and a textbox.

Windows1 (test.exe) reference ILib.dll, and only contains a stackPanel1.

But, why there is nothong in Windows1(stackPanel1)?


回答1:


You are not instantiating the type from the DLL at all. Instead of:

var tmp = Activator.CreateInstance(typeof(UserControl)) as UserControl;

write:

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.



来源:https://stackoverflow.com/questions/3536080/how-to-load-a-usercontrol-in-wpf-with-reflection

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