0

I have two projects for WinUI 3 (Desktop). 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). The library is called 'MyHome.dll'. A page is defined there in XAML. The class for the page is called '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. A XAML parsing error is generated. My question: How do I load a Page (XAML) and the code C #) from a class at runtime.

veikko
  • 89
  • 3

2 Answers2

0

Try to use the method Assembly.LoadFrom() instead of Assembly.LoadFile()

This post describes the difference between this two methods: Difference between LoadFile and LoadFrom with .NET Assemblies?

Here is a simple example for the plug and play method to load modules on runtime.

enter image description here

JWhite
  • 73
  • 1
  • 7
  • Unfortunately that does not work. The XAML parse error persists. Do you have any more ideas? – veikko Jun 30 '21 at 16:14
  • No, I am sorry. You can import the XAML-File in a "fresh"/new WPF project to check if it works there. If the parse error persists you know that the issue is comming from the file and not from the loading process. – JWhite Jul 02 '21 at 13:28
0

The error continues. The code of 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:

<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"

veikko
  • 89
  • 3