Loading a WPF control embedded in a DLL in runtime

[亡魂溺海] 提交于 2020-08-23 09:09:24

问题


In my WPF project, I have a dll that contains several WPF UserControls. I would like, in runtime, to be able to check a parameter in the database (already implemented) and according to that parameter (which is a string) to be able to load a specific UserControl to my View.

The UserControl is actually a Canvas, so it basically just places the correct Canvas on the View according to the database entry.

I don't know if I was clear, so please ask me if you didn't understand the question.

Thanks to all helpers!


回答1:


This concept of loading controls or similar things from a dll at runtime is called Reflection and it is a common way of doing things in certain scenarios. Try to google Reflection in C# you will find a lot of tutorials about it.

Basically you will load the dll at runtime. Then you will look for control. Once you find it you will create its instance and use it. All this will happen at runtime

  UserControl myControl = null;    
  Assembly asm = Assembly.LoadFile(Your dll path);
  Type[] tlist = asm.GetTypes();
  foreach (Type t in tlist)
  {
     if(t.Name == "Your class name" )
     {
         myControl = Activator.CreateInstance(t) as UserControl;
         break;
     }               
  }

Also see this question for reference



来源:https://stackoverflow.com/questions/7872934/loading-a-wpf-control-embedded-in-a-dll-in-runtime

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