简体   繁体   English

在运行时加载嵌入在DLL中的WPF控件

[英]Loading a WPF control embedded in a DLL in runtime

In my WPF project, I have a dll that contains several WPF UserControls. 在我的WPF项目中,我有一个包含多个WPF用户控件的dll。 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. 我希望在运行时能够检查数据库中的一个参数(已实现),并根据该参数(它是一个字符串)将特定的UserControl加载到我的View中。

The UserControl is actually a Canvas, so it basically just places the correct Canvas on the View according to the database entry. UserControl实际上是一个Canvas,因此它基本上只是根据数据库条目将正确的Canvas放置在View上。

I don't know if I was clear, so please ask me if you didn't understand the question. 我不知道我是否清楚,所以请问我是否不明白这个问题。

Thanks to all helpers! 感谢所有帮助者!

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. 这种在运行时从dll中加载控件或类似内容的概念称为反射 ,它是在某些情况下执行操作的常用方法。 Try to google Reflection in C# you will find a lot of tutorials about it. 尝试在C#中使用Google Reflection,您会发现很多关于它的教程。

Basically you will load the dll at runtime. 基本上,您将在运行时加载dll。 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 另请参阅此问题以供参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM