How to load a UserControl in WPF with reflection?

后端 未结 1 1669
野性不改
野性不改 2021-01-07 11:26
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var assm = Assembly.LoadFrom(\"wpflib.dll\");
    foreach (var t in assm.GetTypes())
    {
                


        
相关标签:
1条回答
  • 2021-01-07 11:35

    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.

    0 讨论(0)
提交回复
热议问题