|
| 1 | +--- |
| 2 | +id: host-avalonia-controls-in-winforms |
| 3 | +title: Host Avalonia controls in Windows Forms |
| 4 | +--- |
| 5 | + |
| 6 | +# Host Avalonia controls in Windows Forms |
| 7 | + |
| 8 | +Avalonia controls can be hosted in Windows Forms applications. This enables a step-by-step migration of existing Windows Forms applications to Avalonia. |
| 9 | + |
| 10 | +## Overview |
| 11 | + |
| 12 | +An exemplary Windows Forms application with Avalonia controls requires at least two projects: |
| 13 | + |
| 14 | +1. `YourApp` Cross platform library where you put your Avalonia controls |
| 15 | +2. `YourApp.WinForms` Your existing Windows Forms application |
| 16 | +3. `YourApp.Desktop` (optional) Executable Avalonia application, required only for the Visual Studio Avalonia designer |
| 17 | + |
| 18 | +As Windows Forms is only supported on Microsoft Windows, adding Avalonia controls to your app will not make it cross platform. |
| 19 | + |
| 20 | +## Step-by-step instructions |
| 21 | + |
| 22 | +These instruction assume that you use Visual Studio 2022 with the Avalonia extension. |
| 23 | +You can adjust the steps and leave out the `YourApp.Desktop` project if you are using VS Code or Rider. |
| 24 | + |
| 25 | +1. Create both Avalonia projects |
| 26 | + - In Visual Studio add a new project to your solution |
| 27 | + - Choose _Avalonia C# Project_ |
| 28 | + - Select at least _Desktop_ as target platforms |
| 29 | + - Click _Create_ |
| 30 | + - You should now have a `YourApp` and a `YourApp.Desktop` project in your solution |
| 31 | +2. Add references to your existing Windows Forms project |
| 32 | + - A package reference to `Avalonia.Desktop` |
| 33 | + - A package reference to `Avalonia.Win32.Interoperability` |
| 34 | + - A project reference to `YourApp.csproj` |
| 35 | +3. Add the following lines in your `Program.cs` before you call `Application.Run()` |
| 36 | +```cs |
| 37 | +AppBuilder.Configure<App>() |
| 38 | + .UsePlatformDetect() |
| 39 | + .SetupWithoutStarting(); |
| 40 | +``` |
| 41 | +4. Add an `WinFormsAvaloniaControlHost` control from the Toolbox |
| 42 | +5. Add the following line to your form's constructor after `InitializeComponent()` |
| 43 | +```cs |
| 44 | +winFormsAvaloniaControlHost1.Content = new MainView { DataContext = new MainViewModel() }; |
| 45 | +``` |
| 46 | + |
| 47 | +Now you should see Avalonia's default main view _Welcome to Avalonia_ in your Windows Forms application. |
| 48 | + |
| 49 | +:::info |
| 50 | +You cannot use ReactiveUI for your Windows Forms and Avalonia controls at the same time. |
| 51 | + |
| 52 | +If you want to use it for Avalonia you must register ReactiveUI at the `AppBuilder` with `.UseReactiveUI()` in `Program.cs`. |
| 53 | +Do not include a reference to `ReactiveUI.WinForms` otherwise interactions will not work (see [#16478](https://github.com/AvaloniaUI/Avalonia/discussions/16478)). |
| 54 | +::: |
0 commit comments