Skip to main content

Introduction to Avalonia UI

Avalonia UI Banner

What is Avalonia UI?

Avalonia UI is a modern, powerful, cross-platform UI framework for .NET developers that enables building beautiful, high-performance desktop, mobile, and web applications from a single codebase. It uses its own rendering engine (based on Skia) to draw UI controls, ensuring consistent appearance and behavior across various platforms, including Windows, macOS, Linux, Android, iOS, and WebAssembly.

Unlike Windows Presentation Foundation (WPF) which is limited to Windows, or Universal Windows Platform (UWP) which is limited to the Windows ecosystem, Avalonia UI empowers developers to create applications that can run virtually anywhere .NET runs, without compromising on features or performance.

// The power of Avalonia in a simple Hello World
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace AvaloniaHelloWorld
{
public class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="AvaloniaHelloWorld.MainWindow"
Title="Avalonia Hello World"
Width="400" Height="300">
<StackPanel HorizontalAlignment="Center"
VerticalAlignment="Center">
<TextBlock Text="Hello, Avalonia UI!"
FontSize="24"
FontWeight="Bold"
Foreground="#1E88E5"/>
<Button Content="Click Me"
Margin="0,20,0,0"
Padding="10,5"
HorizontalAlignment="Center"/>
</StackPanel>
</Window>

Avalonia applications are written in C# or F#, making it easy to rapidly prototype applications that can evolve over time into complex, enterprise-grade systems. The framework provides full access to the platform's capabilities and delivers excellent performance through its compositional renderer.

Key Features

FeatureDescription
Cross-PlatformBuild once, run everywhere: Windows, macOS, Linux, Android, iOS, and WebAssembly
XAML UI DesignFamiliar XAML syntax for defining user interfaces, similar to WPF and UWP
Modern ArchitectureBuilt on .NET 6/7/8, leveraging the latest advancements in the .NET ecosystem
Flexible StylingComprehensive styling with CSS-like selectors and theme support
MVVM SupportFirst-class support for the Model-View-ViewModel pattern with ReactiveUI integration
Rich Control LibraryExtensive set of built-in controls, layouts, and third-party component support
Hardware AccelerationGPU-accelerated rendering with support for custom visual effects and animations
Open SourceMIT licensed with an active community and regular updates

When to Use Avalonia UI

Avalonia UI is an excellent choice when:

  • You need to target multiple platforms from a single codebase
  • You want a modern UI framework with XAML support
  • You're familiar with WPF or UWP and want to leverage that knowledge
  • You need a flexible styling system for creating custom themes
  • You want to build desktop applications with .NET that run on non-Windows platforms
  • You need to share UI code between desktop and mobile applications

Comparison with WPF and UWP

While Avalonia UI shares many concepts with WPF and UWP, there are important differences to understand when choosing a framework or migrating existing applications.

Framework Comparison

FeatureAvalonia UIWPFUWP/WinUI
PlatformsWindows, macOS, Linux, Android, iOS, WebAssemblyWindows onlyWindows 10/11 devices only
UI LanguageXAMLXAMLXAML
Programming LanguagesC#, F#C#, VB.NET, F#C#, VB.NET, C++, JavaScript
Rendering EngineSkia (cross-platform)DirectX (Windows-specific)DirectX (Windows-specific)
Minimum .NET Version.NET Standard 2.0, .NET 6+.NET Framework 3.5+, .NET 6+UWP: .NET Native, WinUI 3: .NET 5+
Open SourceYes (MIT License)Yes (MIT License via .NET Foundation)Partially (WinUI is open source)
Control SetModern controls inspired by WPFTraditional Windows controlsModern Fluent Design controls
Styling SystemCSS-like selectors with stylesResources and templatesResources and templates with Fluent Design
Data BindingReactiveUI integration, similar to WPF with enhancementsComprehensiveComprehensive with x:Bind
Hot ReloadYesYes (in newer versions)Yes
Designer SupportLimited (improving)ExtensiveExtensive
Community SizeGrowingLarge, establishedMedium, growing
Mobile SupportNativeNoneUWP: Windows devices only
Web SupportWebAssemblyNoneNone

Key Differences from WPF

Avalonia UI's API is heavily inspired by WPF, making migration relatively straightforward, but there are some notable differences:

// WPF Dependency Property
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register(nameof(Text), typeof(string), typeof(MyControl));

// Avalonia Property
public static readonly StyledProperty<string> TextProperty =
AvaloniaProperty.Register<MyControl, string>(nameof(Text));

Property System

  • Avalonia uses AvaloniaProperty instead of DependencyProperty
  • Property registration syntax is different but conceptually similar
  • Attached properties use a different registration pattern

Styling System

  • Avalonia uses CSS-like selectors for targeting elements:
    <!-- Avalonia Style -->
    <Style Selector="Button.primary">
    <Setter Property="Background" Value="#1E88E5"/>
    </Style>

    <!-- WPF Style -->
    <Style TargetType="Button" x:Key="PrimaryButton">
    <Setter Property="Background" Value="#1E88E5"/>
    </Style>
  • Styles are applied automatically based on selectors, not by explicit references
  • Pseudo-classes like :pointerover replace WPF triggers

Other Differences

  • Control templating has syntax differences
  • Avalonia doesn't support WPF's BitmapEffects (uses different effects system)
  • Animation system is different but conceptually similar
  • Avalonia uses .axaml file extension (though .xaml works too)
  • Different namespace conventions and control class hierarchies

Key Differences from UWP/WinUI

Avalonia UI offers cross-platform capabilities that UWP lacks, but with some important distinctions:

Platform Support

  • Avalonia works across multiple operating systems, not just Windows
  • No direct access to Windows Runtime APIs (though platform-specific code is possible)

UI and Controls

  • Different control styling approach:
    <!-- Avalonia -->
    <Button Classes="accent" Content="Click Me"/>

    <!-- UWP -->
    <Button Style="{StaticResource AccentButtonStyle}" Content="Click Me"/>
  • Similar layout concepts but different implementation details
  • Avalonia doesn't use UWP's adaptive layout system but has its own responsive capabilities

Application Model

  • Different application lifecycle management
  • No concept of app suspension/resumption like in UWP
  • Different navigation patterns and conventions

Migration Considerations

When migrating from WPF or UWP to Avalonia:

  • Start with UI components that have the fewest platform dependencies
  • Use conditional compilation (#if) for platform-specific code
  • Consider a gradual migration approach for large applications
  • Leverage MVVM pattern to separate business logic from UI
  • Use Avalonia's platform-specific APIs for necessary native functionality

Cross-Platform Capabilities

One of Avalonia UI's greatest strengths is its true cross-platform nature. Unlike other frameworks that claim to be cross-platform but have significant limitations, Avalonia delivers a consistent experience across desktop, mobile, and web platforms.

Desktop Platforms

Desktop Platforms

Avalonia UI applications run natively on:

PlatformSupported VersionsRequirements
WindowsWindows 7, 8, 10, 11.NET 6.0+ runtime
macOSmacOS 10.13 (High Sierra) and above.NET 6.0+ runtime
LinuxUbuntu, Fedora, Debian, etc..NET 6.0+ runtime, appropriate graphics libraries
// Platform-specific code example for Windows
#if WINDOWS
// Windows-specific functionality
var windowsPath = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Windows),
"System32");
#endif

Desktop applications benefit from:

  • Native performance on each platform
  • Access to platform-specific APIs when needed
  • Consistent UI rendering across operating systems
  • Support for multiple windows and dialogs
  • Hardware acceleration for smooth animations and effects

Mobile Platforms

Android

Android

iOS

iOS

Avalonia UI provides robust support for mobile platforms:

PlatformSupported VersionsFeatures
AndroidAndroid 5.0 (Lollipop) and aboveTouch input, gestures, native controls
iOSiOS 10 and aboveTouch input, gestures, native controls

Mobile development with Avalonia offers:

  • Touch-optimized UI controls
  • Responsive layouts that adapt to different screen sizes
  • Access to device-specific features through platform-specific code
  • Ability to share business logic and UI code with desktop versions
// Example of platform-specific service implementation
public interface IPhotoPickerService
{
Task<Stream> PickPhotoAsync();
}

#if IOS
public class iOSPhotoPickerService : IPhotoPickerService
{
public async Task<Stream> PickPhotoAsync()
{
// iOS-specific implementation
}
}
#elif ANDROID
public class AndroidPhotoPickerService : IPhotoPickerService
{
public async Task<Stream> PickPhotoAsync()
{
// Android-specific implementation
}
}
#endif

Web Platform

WebAssembly

Avalonia UI can run in web browsers through WebAssembly (WASM), enabling:

  • Deployment of applications to the web without rewriting the UI
  • Sharing code between desktop, mobile, and web versions
  • Progressive Web App (PWA) capabilities
  • Offline functionality

Web deployment considerations:

  • Initial download size is larger than traditional web apps
  • Performance depends on the browser's WebAssembly implementation
  • Some platform-specific features may not be available
  • DOM integration is possible but requires special handling

Project Structure for Cross-Platform Development

When building cross-platform applications with Avalonia UI, a typical solution structure looks like this:

MyApp.sln
├── MyApp (shared project)
│ ├── Models/
│ ├── ViewModels/
│ ├── Views/
│ ├── Services/
│ └── App.axaml
├── MyApp.Desktop (Windows/macOS/Linux)
│ └── Program.cs
├── MyApp.Android
│ └── MainActivity.cs
├── MyApp.iOS
│ └── AppDelegate.cs
└── MyApp.Web
└── Program.cs

This structure allows you to:

  1. Share UI, business logic, and services in the core project
  2. Implement platform-specific features in the platform projects
  3. Use dependency injection or service locator patterns for platform services
  4. Conditionally compile code for specific platforms

Code Sharing Strategies

To maximize code sharing while handling platform differences:

  1. Shared UI with Platform-Specific Adjustments:

    <StackPanel Spacing="{OnPlatform Default=10, iOS=20, Android=15}">
    <!-- Shared UI elements -->
    </StackPanel>
  2. Platform-Specific Services with Common Interface:

    // Register the appropriate implementation based on platform
    services.AddSingleton<IFilePickerService>(
    #if WINDOWS
    new WindowsFilePickerService()
    #elif ANDROID
    new AndroidFilePickerService()
    #elif IOS
    new iOSFilePickerService()
    #else
    new DefaultFilePickerService()
    #endif
    );
  3. Conditional Compilation:

    #if MOBILE
    // Mobile-specific code
    #else
    // Desktop-specific code
    #endif
  4. Platform Detection at Runtime:

    if (OperatingSystem.IsWindows())
    {
    // Windows-specific code
    }
    else if (OperatingSystem.IsMacOS())
    {
    // macOS-specific code
    }

In the following sections, we'll explore how to set up your development environment, create your first Avalonia UI application, and dive deeper into the framework's capabilities.