Setting Up the 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:
Requirement | Details | Download Link |
---|---|---|
.NET SDK | .NET 6.0 or later (8.0 recommended) | dotnet.microsoft.com |
IDE | One of the following: | |
• Visual Studio 2022 | visualstudio.microsoft.com | |
• JetBrains Rider | jetbrains.com/rider | |
• Visual Studio Code | code.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:
Template | Description | Usage |
---|---|---|
avalonia.app | A basic Avalonia UI application | dotnet new avalonia.app -o MyApp |
avalonia.mvvm | An Avalonia UI application with MVVM structure | dotnet new avalonia.mvvm -o MyMvvmApp |
avalonia.xplat | A cross-platform Avalonia UI solution (desktop and mobile) | dotnet new avalonia.xplat -o MyXPlatApp |
avalonia.resource | An Avalonia resource dictionary | dotnet new avalonia.resource -o MyResources |
avalonia.usercontrol | An Avalonia user control | dotnet new avalonia.usercontrol -n MyControl |
avalonia.window | An Avalonia window | dotnet 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:
Creating Projects in Visual Studio 2022
- Go to "File" > "New" > "Project"
- Search for "Avalonia" in the search box
- Select the desired template (e.g., "Avalonia Application")
- Click "Next"
- Enter your project name and location
- Click "Create"
Creating Projects in JetBrains Rider
- Go to "File" > "New" > "Solution"
- Select ".NET" in the left panel
- Search for "Avalonia" in the right panel
- Select the desired template
- Click "Next"
- Enter your project name and location
- Click "Create"
Creating Projects in Visual Studio Code
- Open a terminal in VS Code
- Navigate to your desired directory
- Run the template command (e.g.,
dotnet new avalonia.mvvm -o MyApp
) - Open the created folder in VS Code
- 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
Package | Description |
---|---|
Avalonia | Core Avalonia UI framework |
Avalonia.Desktop | Desktop platform backends (Windows, macOS, Linux) |
Avalonia.Themes.Fluent | Microsoft Fluent Design-inspired theme |
Avalonia.Diagnostics | Development-time debugging tools |
Avalonia.ReactiveUI | Integration 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 logicMyXPlatApp.Desktop
- Desktop application (Windows, macOS, Linux)MyXPlatApp.Android
- Android applicationMyXPlatApp.iOS
- iOS applicationMyXPlatApp.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

JetBrains Rider

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:
- Go to "Extensions" > "Manage Extensions"
- Search for "Avalonia"
- Download and install "Avalonia for Visual Studio"
- Restart Visual Studio
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:
- Go to "Settings" > "Plugins"
- Search for "Avalonia"
- Install "Avalonia.Rider"
- Restart Rider
Visual Studio Code Extensions
For Visual Studio Code users, install these extensions for the best experience:
-
C# Dev Kit by Microsoft
- Provides C# language support
- Debugging capabilities
- Project management
-
Avalonia for VS Code
- XAML syntax highlighting
- Basic IntelliSense for Avalonia XAML
- Snippets for common Avalonia patterns
Installation:
- Open VS Code
- Go to Extensions view (Ctrl+Shift+X)
- Search for and install the extensions
- 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:
- Open an
.axaml
file in your IDE - The previewer should automatically appear (split view)
- As you edit the XAML, the preview updates in real-time
- You can adjust preview settings using the toolbar
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
andd:DesignHeight
: Set the dimensions in the previewerd:IsDesignTimeOnly
: Element only appears in design-timed: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:
-
Install the package:
dotnet add package Avalonia.Diagnostics
-
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
; -
Access DevTools at runtime by pressing
F12
orCtrl+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
-
Follow the MVVM Pattern
- Keep UI logic in views
- Keep business logic in view models
- Use data binding to connect views and view models
-
Use Folder Structure for Organization
- Group related files in appropriate folders
- Consider creating subfolders for complex features
-
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
-
Use Dependency Injection
- Register services in App.axaml.cs
- Inject dependencies into view models
- Use interfaces for testability
-
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.