Right way to use windows XAML host control in Winforms project?

57 Views Asked by At

Goal: I have a winforms project and I wish to use XAML controls in the UI. I plan to do this using Xaml islands

I have imported the following nuget package Microsoft.Toolkit.Forms.UI.XamlHost version 5.1.0(saw that version 6 > onwards had issues and folks reverted to 5.1.0). I tried to add the Xaml Host control in the Winforms designer but when I create an object of the Form , the UI crashes.

I tried using the XAML host control in the code behind instead but that results into a crash as well

My code behind looks like this

public partial class TestForm : Form
{
  public TestForm()
  {
    this.InitializeComponent();
  }

  public void ShowUI()
  {
    WindowsXamlHost windowsXamlHost = new WindowsXamlHost();
    this.Controls.Add(windowsXamlHost);

    Button testButton = new Button();
    testButton.Content = "Test";
           
    windowsXamlHost.Child = testButton;
    this.Show();
    this.BringToFront();
  }
}

I added the following to the app.manifest

<maxversiontested Id="10.0.18295.0"/>
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />

In main.cs

TestForm test = new TestForm();
test.ShowUI();

The UI crashes each time. Can I get help understanding:

  1. Why the UI crashes?
  2. Is the way to use XAML Host control incorrect ?
0

There are 0 best solutions below