[英]Error creating a page (XAML) at runtime from an assembly in WinUi (desktop)
I have two projects for WinUI 3 (Desktop).我有两个 WinUI 3(桌面)项目。 One project is a desktop app and the other project is a class library (for desktop app).
一个项目是桌面应用程序,另一个项目是类库(用于桌面应用程序)。 In the library I would like to define a page in XAML and load it into the desktop app at runtime (plug-in concept).
在库中,我想在 XAML 中定义一个页面并在运行时将其加载到桌面应用程序中(插件概念)。 The library is called 'MyHome.dll'.
该库名为“MyHome.dll”。 A page is defined there in XAML.
在 XAML 中定义了一个页面。 The class for the page is called 'MyHome'.
该页面的类称为“MyHome”。
The code for loading the assembly:加载程序集的代码:
var dir = System.AppDomain.CurrentDomain.BaseDirectory;
Assembly MyHomeAssembly = Assembly.LoadFile (dir + "/MyHome.dll");
var page = (Page) Assembly.CreateInstance ("MyHome.MyHome")
The assembly is loaded.程序集已加载。 With the debugger I can see that the class 'MyHome' is included.
使用调试器,我可以看到包含了“MyHome”类。 A XAML parsing error is generated.
生成 XAML 分析错误。 My question: How do I load a Page (XAML) and the code C #) from a class at runtime.
我的问题:如何在运行时从类加载页面 (XAML) 和代码 C#)。
Try to use the method Assembly.LoadFrom()
instead of Assembly.LoadFile()
尝试使用方法
Assembly.LoadFrom()
而不是Assembly.LoadFile()
This post describes the difference between this two methods: Difference between LoadFile and LoadFrom with .NET Assemblies?这篇文章描述了这两种方法之间的区别: LoadFile 和 LoadFrom 与 .NET 程序集的区别?
Here is a simple example for the plug and play method to load modules on runtime.下面是一个简单的例子,用于在运行时加载模块的即插即用方法。
The error continues.错误继续。 The code of Desktop-App:
Desktop-App 的代码:
private void LoadAssemblys()
{
var dir = System.AppDomain.CurrentDomain.BaseDirectory;
Assembly MyHomeAssembly=Assembly.LoadFrom(dir + "/MyHome.dll");
System.Type[] types = MyHomeAssembly.GetTypes();
System.Type primaryTyp = types[0];
foreach (System.Type t in types)
{
if (t.Name == "MyHomePage")
{
var obj = MyHomeAssembly.CreateInstance("MyHome.MyHomePage", true);
}
}
}
The dll is an simple class-library-Project with xaml-Code: dll 是一个带有 xaml-Code 的简单类库项目:
<Page
x:Class="MyHome.MyHomePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:MyHome"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
mc:Ignorable="d">
<Grid>
</Grid>
</Page>
The error: Microsoft.UI.Xaml.Markup.XamlParseException: "XAML"错误:Microsoft.UI.Xaml.Markup.XamlParseException:“XAML”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.