loading experience

Guide

Guide to Avalonia UI: .NET interfaces for desktop, embedded Linux and the browser

Guide to Avalonia UI: .NET interfaces for desktop, embedded Linux and the browser

A single guide to Avalonia UI: the introduction, the comparison with .NET MAUI, MVVM and compiled bindings, styles and the Fluent theme, embedded Linux, WebAssembly in the browser and migrating from WPF. Each section is a complete article you can read on its own.

In this guide

  1. Avalonia UI: .NET interfaces for Windows, macOS, Linux and beyond
  2. Avalonia or .NET MAUI? A practical comparison
  3. Avalonia: MVVM and compiled bindings
  4. Avalonia: selector-based styles, the Fluent theme and dark mode
  5. Avalonia on embedded Linux: interfaces for panels and machines
  6. Avalonia in the browser with WebAssembly
  7. Migrating from WPF to Avalonia: what really changes

Avalonia UI: .NET interfaces for Windows, macOS, Linux and beyond

Avalonia UI is an open-source framework for building graphical interfaces with C# and XAML that run on Windows, macOS and Linux, as well as iOS, Android, the browser (WebAssembly) and embedded devices.

The same C# and XAML code, looking identical on every platform.
The same C# and XAML code, looking identical on every platform.

How it works

Unlike frameworks that use each system's native controls, Avalonia draws the whole interface itself with its own rendering engine based on Skia. The result is an application that looks identical on every platform, pixel for pixel.

The first project

dotnet new install Avalonia.Templates
dotnet new avalonia.mvvm -o WarehouseManager
cd WarehouseManager
dotnet run
<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="using:WarehouseManager.ViewModels"
        x:Class="WarehouseManager.Views.MainWindow"
        x:DataType="vm:MainWindowViewModel"
        Title="Warehouse manager" Width="900" Height="600">
    <StackPanel Margin="20" Spacing="10">
        <TextBlock Text="{Binding Title}" FontSize="24" />
        <Button Content="Refresh" Command="{Binding RefreshCommand}" />
    </StackPanel>
</Window>

Strengths

  • Linux as a first-class citizen, alongside Windows and macOS.
  • XAML familiar to those coming from WPF, with a styling system inspired by CSS.
  • Performance and Native AOT support for compact applications that start quickly.
  • MIT licence and a very active community.

When to choose it

Business and technical applications that must also run on Linux, industrial tools, interfaces on embedded panels, migrations of old WPF applications to more platforms. For apps designed mainly for phones, with a native look, .NET MAUI remains an alternative worth considering.


Avalonia or .NET MAUI? A practical comparison

Both let you write interfaces in C# and XAML for several platforms, but with different philosophies. The right choice depends on where the application must run and how it should look.

The choice depends on devices and users, not on a ranking.
The choice depends on devices and users, not on a ranking.

Key differences

  • Rendering: MAUI uses each system's native controls; Avalonia draws everything itself, with an identical look everywhere.
  • Linux: Avalonia supports it officially; MAUI does not.
  • Mobile: MAUI was born for phones and tablets, with deep integration into native APIs; Avalonia supports iOS and Android, but its strength is the desktop.
  • Web: Avalonia can run in the browser with WebAssembly; with MAUI you go through Blazor Hybrid.
  • Support: MAUI is part of .NET and maintained by Microsoft; Avalonia is open source with a dedicated company and commercial support options.

XAML side by side

<!-- .NET MAUI -->
<VerticalStackLayout Spacing="8">
    <Label Text="{Binding Name}" />
    <Button Text="Save" Command="{Binding SaveCommand}" />
</VerticalStackLayout>

<!-- Avalonia -->
<StackPanel Spacing="8">
    <TextBlock Text="{Binding Name}" />
    <Button Content="Save" Command="{Binding SaveCommand}" />
</StackPanel>

The concepts are the same, the control names are not: anyone who knows one learns the other quickly, and ViewModels written with CommunityToolkit.Mvvm can be reused unchanged.

How to decide

  • Consumer smartphone app with a native look: .NET MAUI.
  • Desktop business app that must also run on Linux or Mac: Avalonia.
  • Operator panel on an embedded Linux device: Avalonia.
  • Migration from WPF to more systems: Avalonia, closer in concepts.
  • Team with strong web skills: MAUI Blazor Hybrid.

There is no best framework in absolute terms: there is the one that suits your users and your devices. A small prototype with both, on the most complex screens, clears up doubts better than any table.


Avalonia: MVVM and compiled bindings

Avalonia's MVVM template already prepares the structure: Views and ViewModels folders, a ViewLocator that automatically pairs each ViewModel with its view, and compiled bindings enabled by default.

Changing screen means changing the current ViewModel.
Changing screen means changing the current ViewModel.

Compiled bindings

With compiled bindings the XAML compiler checks that every property really exists in the ViewModel: a typo becomes a build error, not an empty field discovered by the user.

<PropertyGroup>
  <AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
</PropertyGroup>
<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:vm="using:Warehouse.ViewModels"
             x:Class="Warehouse.Views.ItemsView"
             x:DataType="vm:ItemsViewModel">
    <DockPanel Margin="16">
        <TextBox DockPanel.Dock="Top" Watermark="Search..." Text="{Binding Filter}" />
        <ListBox ItemsSource="{Binding Items}" SelectedItem="{Binding Selected}">
            <ListBox.ItemTemplate>
                <DataTemplate x:DataType="vm:ItemRow">
                    <TextBlock Text="{Binding Description}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </DockPanel>
</UserControl>

The ViewModel

public partial class ItemsViewModel(ICatalog catalog) : ViewModelBase
{
    [ObservableProperty]
    public partial string Filter { get; set; } = "";

    [ObservableProperty]
    public partial ItemRow? Selected { get; set; }

    public ObservableCollection<ItemRow> Items { get; } = [];

    partial void OnFilterChanged(string value) => _ = RefreshAsync(value);

    private async Task RefreshAsync(string filter)
    {
        var results = await catalog.SearchAsync(filter);
        Items.Clear();
        foreach (var r in results) Items.Add(r);
    }
}

CommunityToolkit.Mvvm works with Avalonia exactly as with MAUI and WPF: the generated On...Changed partial methods let you react to property changes. Alternatively, the template also offers ReactiveUI, widely used in the Avalonia ecosystem.

Navigating between views

A main ViewModel exposes a property holding the current ViewModel; a ContentControl displays it and the ViewLocator picks the right view. Changing screen just means changing that object.


Avalonia: selector-based styles, the Fluent theme and dark mode

Developers coming from WPF find a big novelty in Avalonia: styles are applied with selectors similar to CSS, instead of triggers and resource keys.

From a targeted tweak to the full theme, with CSS-like selectors.
From a targeted tweak to the full theme, with CSS-like selectors.

The base theme

<Application xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="Warehouse.App"
             RequestedThemeVariant="Default">
    <Application.Styles>
        <FluentTheme />
    </Application.Styles>
</Application>

With RequestedThemeVariant="Default" the application follows the operating system's light or dark theme; you can force Light or Dark.

Classes and pseudo-classes

<Window.Styles>
    <Style Selector="Button.primary">
        <Setter Property="Background" Value="#2a8442" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="CornerRadius" Value="8" />
    </Style>
    <Style Selector="Button.primary:pointerover /template/ ContentPresenter">
        <Setter Property="Background" Value="#23703a" />
    </Style>
    <Style Selector="TextBox:error">
        <Setter Property="BorderBrush" Value="Firebrick" />
    </Style>
</Window.Styles>

<Button Classes="primary" Content="Confirm order" />

Classes can also be added and removed from code or through bindings (Classes.active="{Binding IsActive}"), a clean way to change the look based on state.

Resources for both themes

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Light">
                <SolidColorBrush x:Key="PanelBackground" Color="#F4F6F8" />
            </ResourceDictionary>
            <ResourceDictionary x:Key="Dark">
                <SolidColorBrush x:Key="PanelBackground" Color="#1E2226" />
            </ResourceDictionary>
        </ResourceDictionary.ThemeDictionaries>
    </ResourceDictionary>
</Application.Resources>

<Border Background="{DynamicResource PanelBackground}" />

ControlTheme

To completely redesign a control you use a ControlTheme, which defines its template and base styles. For small tweaks, selector-based styles are simpler and stay compatible with Fluent theme updates.


Avalonia on embedded Linux: interfaces for panels and machines

Many industrial devices have a touch screen and a Linux board: operator panels, kiosks, measuring instruments. Avalonia can draw the interface directly on the screen, without a desktop environment, keeping C# and XAML.

You develop on the PC and deploy on the board without changing code.
You develop on the PC and deploy on the board without changing code.

Starting without a desktop

The Linux framebuffer package lets the application start by drawing directly through DRM or the framebuffer, with touch screen input.

public static class Program
{
    public static int Main(string[] args)
    {
        var builder = BuildAvaloniaApp();

        // on the panel: no desktop, draw straight to the screen
        if (args.Contains("--drm"))
            return builder.StartLinuxDrm(args);

        // on the development PC: a normal window
        return builder.StartWithClassicDesktopLifetime(args);
    }

    public static AppBuilder BuildAvaloniaApp() =>
        AppBuilder.Configure<App>().UsePlatformDetect().LogToTrace();
}

The same project runs in a window on the developer's PC and full screen on the device: you develop and test comfortably, and deploy on the board.

Publishing for ARM

dotnet publish -c Release -r linux-arm64 --self-contained true -p:PublishAot=true

With Native AOT the application starts quickly even on modest processors and does not need the .NET runtime installed on the board.

Designing for the field

  • Touch: large buttons, no interactions that require hovering.
  • Readability: high contrast and large fonts, because shop-floor lighting is unpredictable.
  • Robustness: automatic start as a system service and restart on error.
  • Updates: a secure remote update mechanism, designed in from the start.

Combined with industrial protocols such as OPC UA and Modbus, Avalonia makes it possible to build modern machine interfaces with the same skills used for business applications.


Avalonia in the browser with WebAssembly

Avalonia can run an application directly in the browser thanks to WebAssembly: the .NET code is downloaded and executed by the browser, and the interface is drawn inside an area of the page.

The interface code is one, the startup projects are tiny.
The interface code is one, the startup projects are tiny.

One project, several targets

dotnet new avalonia.xplat -o Quotes

The cross-platform template creates a shared project with views and ViewModels and a "startup" project for each target: desktop, browser, Android and iOS. The browser project is very small:

internal sealed partial class Program
{
    private static Task Main(string[] args) =>
        BuildAvaloniaApp().StartBrowserAppAsync("out");

    public static AppBuilder BuildAvaloniaApp() =>
        AppBuilder.Configure<App>();
}

The string "out" is the id of the HTML element in which the application is drawn.

When it makes sense

  • Offering an online version of an existing desktop tool, for example a configurator or a technical calculator.
  • Demos and free trials with no installation.
  • Internal tools to be used even from workstations where software cannot be installed.

Limits to be aware of

  • The first load downloads the runtime and the application: optimise it with trimming and compression.
  • The code runs inside the browser sandbox: no free access to files and network, HTTP calls subject to CORS rules.
  • For a public site indexed by search engines, server-generated HTML remains the right choice.

Used in the right place, it lets you reach users through the browser while reusing every last line of the desktop application's code.


Migrating from WPF to Avalonia: what really changes

WPF only runs on Windows. When an application must also reach macOS or Linux, Avalonia is the most natural destination: XAML and concepts are similar, but not identical.

First secure the logic, then rewrite the views.
First secure the logic, then rewrite the views.

Main differences

  • Files: views use the .axaml extension and the https://github.com/avaloniaui namespace.
  • Visibility: instead of Visibility you use the boolean IsVisible property.
  • Triggers: they do not exist; you use styles with selectors, classes and pseudo-classes.
  • Dependency properties: they become StyledProperty or DirectProperty.
  • References to other elements: in bindings you write #elementName.Property.

A custom property

// WPF
public static readonly DependencyProperty HeaderProperty =
    DependencyProperty.Register(nameof(Header), typeof(string), typeof(Card));

// Avalonia
public static readonly StyledProperty<string> HeaderProperty =
    AvaloniaProperty.Register<Card, string>(nameof(Header), "");

public string Header
{
    get => GetValue(HeaderProperty);
    set => SetValue(HeaderProperty, value);
}

A trigger becomes a style

<!-- in WPF: DataTrigger on Status = "Error" -->
<Style Selector="Border.error">
    <Setter Property="Background" Value="MistyRose" />
</Style>

<Border Classes.error="{Binding HasErrors}" />

A migration strategy

  1. Separate the logic: move ViewModels and services into modern .NET libraries with no WPF dependencies. They are one hundred percent reusable.
  2. Rewrite the views starting from the simplest screens, adapting styles and triggers.
  3. Replace third-party controls with Avalonia equivalents, such as DataGrid or compatible charting libraries.
  4. Test on every system: fonts, display scaling and file paths change from one system to another.

For very large applications there is also Avalonia XPF, a commercial product that runs existing WPF applications on several platforms with almost no changes: an option worth considering when rewriting the views is not sustainable.


Comments (0)

No comments yet.

Leave a comment