Skip to main content

Setting Up the Environment

Avalonia Development Environment

Before you can start developing applications with Avalonia UI, you need to set up your development environment. This section will guide you through the installation process, project setup, and introduce you to the development tools available for Avalonia UI development.

Installation and Project Setup

Prerequisites

To develop Avalonia UI applications, you'll need:

RequirementDetailsDownload Link
.NET SDK.NET 6.0 or later (8.0 recommended)dotnet.microsoft.com
IDEOne of the following:
• Visual Studio 2022visualstudio.microsoft.com
• JetBrains Riderjetbrains.com/rider
• Visual Studio Codecode.visualstudio.com

IDE-Specific Requirements

For Visual Studio 2022:

  • .NET Desktop Development workload
  • Optional: Mobile Development with .NET workload (for Android/iOS)

For JetBrains Rider:

  • No additional requirements, Rider includes all necessary .NET tools

For Visual Studio Code:

  • C# Dev Kit extension
  • .NET SDK installed separately

Installing Avalonia Templates

The easiest way to get started with Avalonia UI is to install the project templates. Open a command prompt or terminal and run:

dotnet new install Avalonia.Templates

This command installs the following templates:

TemplateDescriptionUsage
avalonia.appA basic Avalonia UI applicationdotnet new avalonia.app -o MyApp
avalonia.mvvmAn Avalonia UI application with MVVM structuredotnet new avalonia.mvvm -o MyMvvmApp
avalonia.xplatA cross-platform Avalonia UI solution (desktop and mobile)dotnet new avalonia.xplat -o MyXPlatApp
avalonia.resourceAn Avalonia resource dictionarydotnet new avalonia.resource -o MyResources
avalonia.usercontrolAn Avalonia user controldotnet new avalonia.usercontrol -n MyControl
avalonia.windowAn Avalonia windowdotnet new avalonia.window -n MyWindow

You can verify the installation by listing all available templates:

dotnet new list

Look for the Avalonia templates in the output to confirm they were installed correctly.

Creating Your First Project

Once the templates are installed, you can create a new Avalonia UI project using the .NET CLI:

# Create a basic Avalonia application
dotnet new avalonia.app -o MyAvaloniaApp

# Create an MVVM-structured Avalonia application
dotnet new avalonia.mvvm -o MyAvaloniaMvvmApp

# Create a cross-platform Avalonia solution
dotnet new avalonia.xplat -o MyXPlatApp

After creating your project, navigate to the project directory and run it:

cd MyAvaloniaApp
dotnet run

You should see a window like this:

Avalonia Default Window

Creating Projects in Visual Studio 2022

  1. Go to "File" > "New" > "Project"
  2. Search for "Avalonia" in the search box
  3. Select the desired template (e.g., "Avalonia Application") Visual Studio New Project Dialog
  4. Click "Next"
  5. Enter your project name and location
  6. Click "Create"

Creating Projects in JetBrains Rider

  1. Go to "File" > "New" > "Solution"
  2. Select ".NET" in the left panel
  3. Search for "Avalonia" in the right panel
  4. Select the desired template
  5. Click "Next"
  6. Enter your project name and location
  7. Click "Create"

Creating Projects in Visual Studio Code

  1. Open a terminal in VS Code
  2. Navigate to your desired directory
  3. Run the template command (e.g., dotnet new avalonia.mvvm -o MyApp)
  4. Open the created folder in VS Code
  5. Install the C# Dev Kit extension if not already installed

Installing Required NuGet Packages

If you're adding Avalonia UI to an existing project, you'll need to install the required NuGet packages:

# For a desktop application
dotnet add package Avalonia
dotnet add package Avalonia.Desktop
dotnet add package Avalonia.Themes.Fluent
dotnet add package Avalonia.Diagnostics # For runtime debugging tools

# For ReactiveUI integration (recommended for MVVM)
dotnet add package Avalonia.ReactiveUI

Or using the Package Manager Console in Visual Studio:

Install-Package Avalonia
Install-Package Avalonia.Desktop
Install-Package Avalonia.Themes.Fluent
Install-Package Avalonia.Diagnostics
Install-Package Avalonia.ReactiveUI

Package Descriptions

PackageDescription
AvaloniaCore Avalonia UI framework
Avalonia.DesktopDesktop platform backends (Windows, macOS, Linux)
Avalonia.Themes.FluentMicrosoft Fluent Design-inspired theme
Avalonia.DiagnosticsDevelopment-time debugging tools
Avalonia.ReactiveUIIntegration with ReactiveUI MVVM framework

Mobile Development Setup

For mobile development, you'll need additional workloads and tools:

Prerequisites for Mobile Development

  • For Android:

    • Android SDK
    • Java Development Kit (JDK)
  • For iOS:

    • macOS computer
    • Xcode installed
    • Apple Developer account (for device deployment)

Installing .NET Workloads

# Install required workloads
dotnet workload install android ios

Creating a Cross-Platform Solution

# Create a cross-platform solution with mobile support
dotnet new avalonia.xplat -o MyXPlatApp

This creates a solution with the following projects:

  • MyXPlatApp - Core project with shared UI and logic
  • MyXPlatApp.Desktop - Desktop application (Windows, macOS, Linux)
  • MyXPlatApp.Android - Android application
  • MyXPlatApp.iOS - iOS application
  • MyXPlatApp.Browser - WebAssembly application (optional)

Running on Mobile Emulators

Android:

# Navigate to the Android project
cd MyXPlatApp.Android

# Run on the default emulator
dotnet build -t:Run

iOS (requires macOS):

# Navigate to the iOS project
cd MyXPlatApp.iOS

# Run on the iOS simulator
dotnet build -t:Run

Development Tools

Avalonia UI development is supported by several tools that enhance the development experience. These tools provide features like XAML previewing, code completion, and debugging capabilities.

IDE Extensions and Plugins

Visual Studio

Visual Studio

Rider

JetBrains Rider

VS Code

Visual Studio Code

Visual Studio Extension

The Avalonia for Visual Studio extension provides essential tools for Avalonia UI development:

Features:

  • XAML previewer with live updates
  • Project and item templates
  • Enhanced IntelliSense for Avalonia XAML
  • Property grid for visual editing
  • Debugging tools integration

Installation:

  1. Go to "Extensions" > "Manage Extensions"
  2. Search for "Avalonia"
  3. Download and install "Avalonia for Visual Studio"
  4. Restart Visual Studio

Avalonia VS Extension

JetBrains Rider Plugin

The Avalonia.Rider plugin enhances Rider with Avalonia-specific features:

Features:

  • XAML previewer with live updates
  • Code completion for Avalonia-specific XAML
  • Navigation between XAML and code-behind
  • Live templates for common Avalonia patterns
  • Color picker and other visual tools

Installation:

  1. Go to "Settings" > "Plugins"
  2. Search for "Avalonia"
  3. Install "Avalonia.Rider"
  4. Restart Rider

Avalonia Rider Plugin

Visual Studio Code Extensions

For Visual Studio Code users, install these extensions for the best experience:

  1. C# Dev Kit by Microsoft

    • Provides C# language support
    • Debugging capabilities
    • Project management
  2. Avalonia for VS Code

    • XAML syntax highlighting
    • Basic IntelliSense for Avalonia XAML
    • Snippets for common Avalonia patterns

Installation:

  1. Open VS Code
  2. Go to Extensions view (Ctrl+Shift+X)
  3. Search for and install the extensions
  4. Reload VS Code when prompted

Avalonia XAML Previewer

The XAML previewer is a powerful tool that shows a live preview of your UI as you code. It's available in Visual Studio and Rider through their respective extensions.

Features:

  • Live preview of XAML changes
  • Multiple device/screen size previews
  • Theme switching (Light/Dark)
  • Interactive elements (in some cases)

Using the Previewer:

  1. Open an .axaml file in your IDE
  2. The previewer should automatically appear (split view)
  3. As you edit the XAML, the preview updates in real-time
  4. You can adjust preview settings using the toolbar

XAML Previewer

Design-Time Features

Avalonia UI provides several design-time features to enhance the development experience:

Design-Time Properties

Use design-time properties to control how your UI appears in the previewer without affecting runtime:

<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="MyApp.MainWindow">
<!-- Window content -->
</Window>

Common design-time properties:

  • d:DesignWidth and d:DesignHeight: Set the dimensions in the previewer
  • d:IsDesignTimeOnly: Element only appears in design-time
  • d:DataContext: Set a design-time data context

Design-Time Data Context

Provide sample data for the previewer to show a realistic representation of your UI:

<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:MyApp.ViewModels"
mc:Ignorable="d" d:DesignWidth="400" d:DesignHeight="300"
x:Class="MyApp.Views.UserProfileView">

<!-- Design-time data context -->
<Design.DataContext>
<vm:UserProfileViewModel>
<x:Arguments>
<x:String>John Doe</x:String>
<x:String>https://example.com/avatar.jpg</x:String>
</x:Arguments>
</vm:UserProfileViewModel>
</Design.DataContext>

<!-- View content -->
<StackPanel Spacing="10" Margin="20">
<TextBlock Text="{Binding Username}" FontSize="24" FontWeight="Bold"/>
<Image Source="{Binding AvatarUrl}" Width="100" Height="100"/>
<TextBlock Text="{Binding Bio}" TextWrapping="Wrap"/>
</StackPanel>
</UserControl>

Design-Time Resources

You can also provide design-time specific resources:

<Application.Styles>
<!-- Regular application styles -->
<FluentTheme />

<!-- Design-time only styles -->
<Style Selector="TextBlock" d:IsDesignTimeOnly="True">
<Setter Property="Background" Value="#22FF0000"/>
</Style>
</Application.Styles>

Runtime Debugging Tools

Avalonia includes the DevTools package for runtime inspection and debugging:

  1. Install the package:

    dotnet add package Avalonia.Diagnostics
  2. Enable DevTools in your application:

    // In Program.cs, modify BuildAvaloniaApp method
    public static AppBuilder BuildAvaloniaApp()
    => AppBuilder.Configure<App>()
    .UsePlatformDetect()
    .LogToTrace()
    .WithInterFont()
    #if DEBUG
    .UseDevTools() // Add this line for development builds
    #endif
    ;
  3. Access DevTools at runtime by pressing F12 or Ctrl+Shift+D in your running application

Project Structure

Understanding the structure of an Avalonia UI project is essential for effective development. Avalonia projects follow a consistent organization pattern that helps maintain clean separation of concerns.

Basic Project Structure

A typical Avalonia UI application has the following structure:

MyAvaloniaApp/
├── App.axaml # Application definition and global resources
├── App.axaml.cs # Application code-behind
├── Assets/ # Application assets (images, fonts, etc.)
│ ├── avalonia-logo.ico
│ └── Images/
├── Models/ # Data models (for MVVM)
├── ViewModels/ # View models (for MVVM)
├── Views/ # UI views
│ ├── MainWindow.axaml # Main window XAML
│ └── MainWindow.axaml.cs # Main window code-behind
├── Program.cs # Application entry point
└── ViewLocator.cs # Maps view models to views (MVVM)

MVVM Project Structure

An MVVM-structured Avalonia UI application follows a more organized pattern:

MyAvaloniaMvvmApp/
├── App.axaml
├── App.axaml.cs
├── Assets/
│ ├── avalonia-logo.ico
│ └── Images/
├── Models/ # Data models
│ ├── User.cs
│ └── AppSettings.cs
├── Services/ # Application services
│ ├── IDataService.cs
│ └── DataService.cs
├── ViewModels/ # View models
│ ├── ViewModelBase.cs # Base class for view models
│ ├── MainWindowViewModel.cs
│ └── UserProfileViewModel.cs
├── Views/ # UI views
│ ├── MainWindow.axaml
│ ├── MainWindow.axaml.cs
│ ├── UserProfileView.axaml
│ └── UserProfileView.axaml.cs
├── Styles/ # Custom styles and themes
│ ├── Colors.axaml
│ └── ButtonStyles.axaml
├── Controls/ # Custom controls
│ ├── CustomButton.axaml
│ └── CustomButton.axaml.cs
├── Converters/ # Value converters
│ └── BoolToVisibilityConverter.cs
├── Program.cs
└── ViewLocator.cs

Cross-Platform Project Structure

A cross-platform Avalonia UI solution uses a multi-project structure to target different platforms:

MyXPlatApp/
├── MyXPlatApp/ # Core project (shared code)
│ ├── App.axaml
│ ├── App.axaml.cs
│ ├── Assets/
│ ├── Models/
│ ├── ViewModels/
│ ├── Views/
│ └── Services/
│ ├── IFilePickerService.cs # Platform-agnostic interface
│ └── ILocationService.cs
├── MyXPlatApp.Desktop/ # Desktop-specific project
│ ├── Program.cs # Desktop entry point
│ └── Services/
│ ├── DesktopFilePickerService.cs # Windows/macOS/Linux implementation
│ └── DesktopLocationService.cs
├── MyXPlatApp.Android/ # Android-specific project
│ ├── MainActivity.cs # Android entry point
│ ├── AndroidManifest.xml
│ └── Services/
│ ├── AndroidFilePickerService.cs # Android implementation
│ └── AndroidLocationService.cs
├── MyXPlatApp.iOS/ # iOS-specific project
│ ├── AppDelegate.cs # iOS entry point
│ ├── Info.plist
│ └── Services/
│ ├── iOSFilePickerService.cs # iOS implementation
│ └── iOSLocationService.cs
└── MyXPlatApp.Browser/ # WebAssembly-specific project
├── Program.cs # Browser entry point
├── index.html
└── Services/
├── BrowserFilePickerService.cs # Browser implementation
└── BrowserLocationService.cs

Key Files Explained

App.axaml

The App.axaml file defines application-wide resources, styles, and startup behavior:

<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyAvaloniaApp"
x:Class="MyAvaloniaApp.App">
<Application.DataTemplates>
<local:ViewLocator/>
</Application.DataTemplates>

<Application.Styles>
<FluentTheme/>
<!-- Custom styles -->
<StyleInclude Source="/Styles/Colors.axaml"/>
<StyleInclude Source="/Styles/ButtonStyles.axaml"/>
</Application.Styles>

<Application.Resources>
<!-- Global resources -->
<SolidColorBrush x:Key="PrimaryBrush">#1E88E5</SolidColorBrush>
<SolidColorBrush x:Key="SecondaryBrush">#26A69A</SolidColorBrush>
</Application.Resources>
</Application>

App.axaml.cs

The App.axaml.cs file contains application initialization code:

using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using MyAvaloniaApp.ViewModels;
using MyAvaloniaApp.Views;

namespace MyAvaloniaApp
{
public partial class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}

public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
// Set up dependency injection
var services = ConfigureServices();

// Create main window with view model
desktop.MainWindow = new MainWindow
{
DataContext = new MainWindowViewModel(services)
};
}

base.OnFrameworkInitializationCompleted();
}

private IServiceProvider ConfigureServices()
{
// Set up your dependency injection container here
var services = new ServiceCollection();

// Register services
services.AddSingleton<IDataService, DataService>();

return services.BuildServiceProvider();
}
}
}

Program.cs

The Program.cs file contains the application entry point:

using Avalonia;
using Avalonia.ReactiveUI;
using System;

namespace MyAvaloniaApp
{
/// <summary>
/// The main entry point class for the application.
/// </summary>
public class Program
{
/// <summary>
/// Application entry point. Initializes and starts the Avalonia application.
/// </summary>
/// <param name="args">Command line arguments passed to the application.</param>
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);

/// <summary>
/// Configures the Avalonia application with necessary settings.
/// </summary>
/// <returns>A configured AppBuilder instance ready to start the application.</returns>
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace()
.UseReactiveUI() // Enable ReactiveUI integration
.WithInterFont() // Use Inter font family
#if DEBUG
.UseDevTools() // Enable developer tools in debug builds
#endif
;
}
}

ViewLocator.cs

The ViewLocator.cs file maps view models to views in MVVM applications:

using Avalonia.Controls;
using Avalonia.Controls.Templates;
using MyAvaloniaApp.ViewModels;
using System;

namespace MyAvaloniaApp
{
/// <summary>
/// Maps view models to views based on naming convention.
/// </summary>
public class ViewLocator : IDataTemplate
{
public Control Build(object data)
{
var name = data.GetType().FullName!.Replace("ViewModel", "View");
var type = Type.GetType(name);

if (type != null)
{
return (Control)Activator.CreateInstance(type)!;
}

return new TextBlock { Text = $"View not found: {name}" };
}

public bool Match(object data)
{
return data is ViewModelBase;
}
}
}

Best Practices for Project Organization

  1. Follow the MVVM Pattern

    • Keep UI logic in views
    • Keep business logic in view models
    • Use data binding to connect views and view models
  2. Use Folder Structure for Organization

    • Group related files in appropriate folders
    • Consider creating subfolders for complex features
  3. Maintain Clean Separation of Concerns

    • Use interfaces for platform-specific services
    • Implement platform-specific code in platform projects
    • Keep shared code in the core project
  4. Use Dependency Injection

    • Register services in App.axaml.cs
    • Inject dependencies into view models
    • Use interfaces for testability
  5. Organize Resources Properly

    • Application-wide resources in App.axaml
    • Feature-specific resources in separate files
    • Use merged dictionaries for better organization

In the next section, we'll explore how to create basic UI elements in Avalonia UI.