Host Avalonia controls in Windows Forms
Avalonia controls can be hosted in Windows Forms applications. This enables a step-by-step migration of existing Windows Forms applications to Avalonia.
Overview
An exemplary Windows Forms application with Avalonia controls requires at least two projects:
YourApp
Cross platform library where you put your Avalonia controlsYourApp.WinForms
Your existing Windows Forms applicationYourApp.Desktop
(optional) Executable Avalonia application, required only for the Visual Studio Avalonia designer
As Windows Forms is only supported on Microsoft Windows, adding Avalonia controls to your app will not make it cross platform.
Step-by-step instructions
These instruction assume that you use Visual Studio 2022 with the Avalonia extension.
You can adjust the steps and leave out the YourApp.Desktop
project if you are using VS Code or Rider.
- Create both Avalonia projects
- In Visual Studio add a new project to your solution
- Choose Avalonia C# Project
- Select at least Desktop as target platforms
- Click Create
- You should now have a
YourApp
and aYourApp.Desktop
project in your solution
- Add references to your existing Windows Forms project
- A package reference to
Avalonia.Desktop
- A package reference to
Avalonia.Win32.Interoperability
- A project reference to
YourApp.csproj
- A package reference to
- Add the following lines in your
Program.cs
before you callApplication.Run()
AppBuilder.Configure<App>()
.UsePlatformDetect()
.SetupWithoutStarting();
- Add an
WinFormsAvaloniaControlHost
control from the Toolbox - Add the following line to your form's constructor after
InitializeComponent()
winFormsAvaloniaControlHost1.Content = new MainView { DataContext = new MainViewModel() };
Now you should see Avalonia's default main view Welcome to Avalonia in your Windows Forms application.
You cannot use ReactiveUI for your Windows Forms and Avalonia controls at the same time.
If you want to use it for Avalonia you must register ReactiveUI at the AppBuilder
with .UseReactiveUI()
in Program.cs
.
Do not include a reference to ReactiveUI.WinForms
otherwise interactions will not work (see #16478).