---
name: avalonia-api
description: Comprehensive reference for Avalonia UI framework including XAML syntax, controls, data binding, MVVM patterns, styling, custom controls, layout system, and best practices. Covers ReactiveUI integration, compiled bindings, dependency properties, attached properties, control templates, and cross-platform development patterns.
metadata:
keywords:
- avalonia
- axaml
- xaml
- ui
- mvvm
- reactiveui
- databinding
- controls
- styling
- templates
- cross-platform
- dependency-properties
- attached-properties
- contextmenu
- contextflyout
- menuflyout
- fluentavalonia
version: 1.1.0
last_updated: 2026-02-19
---
# Avalonia UI Framework - Complete API & Best Practices Guide
> **Target Framework**: .NET 10.0+
> **File Extension**: `.axaml` (Avalonia XAML)
> **Official Docs**: https://docs.avaloniaui.net/
---
## Table of Contents
1. [AXAML Fundamentals](#axaml-fundamentals)
2. [Controls & UI Elements](#controls--ui-elements)
3. [Layout System](#layout-system)
4. [Data Binding](#data-binding)
5. [MVVM Pattern with ReactiveUI](#mvvm-pattern-with-reactiveui)
6. [Styling & Theming](#styling--theming)
7. [Dependency & Attached Properties](#dependency--attached-properties)
8. [Custom Controls](#custom-controls)
9. [Control Templates](#control-templates)
10. [Resources & Converters](#resources--converters)
11. [Events & Commands](#events--commands)
12. [Cross-Platform Patterns](#cross-platform-patterns)
13. [Performance & Best Practices](#performance--best-practices)
14. [Common Patterns in XerahS](#common-patterns-in-xerahs)
---
## AXAML Fundamentals
### File Structure
Every `.axaml` file follows this standard structure:
```xml
```
### Required Namespace Declarations
| Namespace | Purpose | Required |
|-----------|---------|----------|
| `xmlns="https://github.com/avaloniaui"` | Core Avalonia controls | ✅ Always |
| `xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"` | XAML language features | ✅ Always |
| `xmlns:vm="using:YourNamespace.ViewModels"` | ViewModel references | ⚠️ For MVVM |
| `xmlns:local="using:YourNamespace"` | Local types/controls | 🔹 As needed |
### Custom Namespace Syntax
```xml
```
### Control Content vs. Attributes
```xml
```
---
## Controls & UI Elements
### Common Built-in Controls
#### Input Controls
- **TextBox**: Single/multi-line text input
- **PasswordBox**: Masked password input
- **NumericUpDown**: Numeric input with increment/decrement
- **CheckBox**: Boolean toggle
- **RadioButton**: Mutually exclusive selection
- **Slider**: Continuous range selection
- **ComboBox**: Dropdown selection
- **AutoCompleteBox**: Text input with suggestions
- **DatePicker**: Date selection
- **TimePicker**: Time selection
- **ColorPicker**: Color selection
#### Display Controls
- **TextBlock**: Read-only text display
- **Label**: Text with access key support
- **Image**: Display images
- **Border**: Visual border around content
- **ContentControl**: Single content container
#### Layout Panels
- **Panel**: Basic container (fills available space)
- **StackPanel**: Vertical/horizontal stack
- **Grid**: Row/column grid layout
- **DockPanel**: Edge-docked layout
- **Canvas**: Absolute positioning
- **WrapPanel**: Wrapping flow layout
- **RelativePanel**: Relative positioning
- **UniformGrid**: Equal-sized cells
#### Lists & Collections
- **ListBox**: Selectable list
- **ListView**: List with view customization
- **TreeView**: Hierarchical tree
- **DataGrid**: Tabular data with columns
- **ItemsControl**: Base collection display
- **ItemsRepeater**: Virtualizing collection
#### Containers
- **Window**: Top-level window
- **UserControl**: Reusable UI component
- **ScrollViewer**: Scrollable content
- **Expander**: Collapsible content
- **TabControl**: Tabbed interface
- **SplitView**: Hamburger menu pattern
#### Buttons
- **Button**: Standard button
- **ToggleButton**: Two-state button
- **RepeatButton**: Auto-repeating button
- **RadioButton**: Mutually exclusive button
- **SplitButton**: Button with dropdown
- **DropDownButton**: Dropdown menu button
#### Advanced
- **Carousel**: Cycling content display
- **MenuFlyout**: Modern flyout-based context menu (⚠️ **Use this with FluentAvalonia**)
- **ContextFlyout**: Right-click menu container (⚠️ **Preferred over ContextMenu**)
- **ContextMenu**: Legacy right-click menu (⚠️ **Avoid with FluentAvalonia theme**)
- **Menu**: Menu bar
- **ToolTip**: Hover information
- **Flyout**: Popup overlay
- **Calendar**: Calendar display
---
## Layout System
### Layout Process
Avalonia uses a two-pass layout system:
1. **Measure Pass**: Determines desired size of each control
2. **Arrange Pass**: Positions controls within available space
```
Control → Measure → MeasureOverride → DesiredSize
→ Arrange → ArrangeOverride → FinalSize
```
### Panel Comparison
| Panel | Use Case | Performance | Complexity |
|-------|----------|-------------|------------|
| **Panel** | Fill available space | ⚡ Best | Simple |
| **StackPanel** | Linear stack | ⚡ Good | Simple |
| **Canvas** | Absolute positioning | ⚡ Good | Simple |
| **DockPanel** | Edge docking | ✅ Good | Medium |
| **Grid** | Complex layouts | ⚠️ Moderate | Complex |
| **RelativePanel** | Relative constraints | ⚠️ Moderate | Complex |
**Recommendation**: Use `Panel` instead of `Grid` with no rows/columns for better performance.
### Common Layout Properties
```xml
Height="50"
MinWidth="50"
MaxWidth="200"
Margin="10,5,10,5"
Padding="5"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center" />
```
### Grid Layout
```xml
ColumnDefinitions="200,*,Auto">
```
### DockPanel Layout
```xml
```
### StackPanel Layout
```xml
Spacing="10">
```
---
## Data Binding
### Binding Syntax
```xml
```
### Compiled Bindings (Recommended)
Compiled bindings provide **compile-time safety** and **better performance**.
```xml
true
```
**Best Practice**: Always use compiled bindings for type safety and performance.
### DataContext Type Inference (v11.3+)
```xml
```
### Multi-Binding
```xml
```
### Element Binding
```xml
```
---
## MVVM Pattern with ReactiveUI
### Setup
```xml
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure()
.UsePlatformDetect()
.LogToTrace()
.UseReactiveUI(); // ← Enable ReactiveUI
```
### Install Package
```bash
dotnet add package ReactiveUI.Avalonia
```
### ViewModel Base Pattern
```csharp
using ReactiveUI;
using System.Reactive;
public class MainViewModel : ReactiveObject
{
private string _firstName = string.Empty;
public string FirstName
{
get => _firstName;
set => this.RaiseAndSetIfChanged(ref _firstName, value);
}
private bool _isLoading;
public bool IsLoading
{
get => _isLoading;
set => this.RaiseAndSetIfChanged(ref _isLoading, value);
}
// Reactive command
public ReactiveCommand SaveCommand { get; }
public MainViewModel()
{
// Command with validation
var canSave = this.WhenAnyValue(
x => x.FirstName,
x => !string.IsNullOrWhiteSpace(x));
SaveCommand = ReactiveCommand.CreateFromTask(
SaveAsync,
canSave);
}
private async Task SaveAsync()
{
IsLoading = true;
try
{
await Task.Delay(1000); // Simulate save
}
finally
{
IsLoading = false;
}
}
}
```
### View Activation
```csharp
public partial class MainView : ReactiveUserControl
{
public MainView()
{
InitializeComponent();
this.WhenActivated(disposables =>
{
// Bind ViewModel properties to View
this.Bind(ViewModel,
vm => vm.FirstName,
v => v.FirstNameTextBox.Text)
.DisposeWith(disposables);
// One-way binding
this.OneWayBind(ViewModel,
vm => vm.IsLoading,
v => v.LoadingSpinner.IsVisible)
.DisposeWith(disposables);
// Bind commands
this.BindCommand(ViewModel,
vm => vm.SaveCommand,
v => v.SaveButton)
.DisposeWith(disposables);
});
}
}
```
---
## Styling & Theming
### Style Types
Avalonia has three styling mechanisms:
1. **Styles**: Similar to CSS, target controls by type or class
2. **Control Themes**: Complete visual templates (like WPF Styles)
3. **Container Queries**: Responsive styles based on container size
### Basic Styles
```xml
```
### Pseudo-classes
```xml
```
### Template Parts
```csharp
[TemplatePart("PART_ContentPresenter", typeof(ContentPresenter))]
public class MyTemplatedControl : TemplatedControl
{
private ContentPresenter? _presenter;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_presenter = e.NameScope.Find("PART_ContentPresenter");
}
}
```
---
## Resources & Converters
### Value Converters
```csharp
public class BoolToVisibilityConverter : IValueConverter
{
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is bool boolValue)
return boolValue ? true : false; // Or specific logic
return false;
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is bool visible)
return visible;
return false;
}
}
```
```xml
```
### Built-in Converters
```xml
```
---
## Events & Commands
### Event Handlers
```xml
```
```csharp
private void OnButtonClick(object? sender, RoutedEventArgs e)
{
// Handle event
}
```
### Commands (MVVM)
```xml
```
```csharp
// Using ReactiveUI
public ReactiveCommand