loading experience

Avalonia UI

Migrating from WPF to Avalonia: what really changes

Properties, styles, triggers and controls: a practical guide to bringing a WPF application to Windows, macOS and Linux.

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