在运行时加载嵌入在

在运行时加载嵌入在

本文介绍了在运行时加载嵌入在 DLL 中的 WPF 控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 WPF 项目中,我有一个包含多个 WPF UserControl 的 dll.我希望在运行时能够检查数据库中的参数(已实现)并根据该参数(它是一个字符串)能够将特定的 UserControl 加载到我的视图中.

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.

UserControl 实际上是一个 Canvas,所以它基本上只是根据数据库条目将正确的 Canvas 放置在 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.

感谢所有帮助者!

推荐答案

这种在运行时从 dll 加载控件或类似内容的概念称为 Reflection 并且它是在某些情况下做事的常见方式.尝试在 C# 中谷歌反射,你会发现很多关于它的教程.

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.

基本上,您将在运行时加载 dll.然后你会寻找控制.找到它后,您将创建它的实例并使用它.这一切都将在运行时发生

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;
     }
  }

另见这个问题以供参考

这篇关于在运行时加载嵌入在 DLL 中的 WPF 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:07