loading experience

Avalonia UI

Avalonia: selector-based styles, the Fluent theme and dark mode

Avalonia's styling system resembles CSS: classes, pseudo-classes and light and dark themes.

Avalonia: selector-based styles, the Fluent theme and dark mode

Developers coming from WPF find a big novelty in Avalonia: styles are applied with selectors similar to CSS, instead of triggers and resource keys.

From a targeted tweak to the full theme, with CSS-like selectors.
From a targeted tweak to the full theme, with CSS-like selectors.

The base theme

<Application xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="Warehouse.App"
             RequestedThemeVariant="Default">
    <Application.Styles>
        <FluentTheme />
    </Application.Styles>
</Application>

With RequestedThemeVariant="Default" the application follows the operating system's light or dark theme; you can force Light or Dark.

Classes and pseudo-classes

<Window.Styles>
    <Style Selector="Button.primary">
        <Setter Property="Background" Value="#2a8442" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="CornerRadius" Value="8" />
    </Style>
    <Style Selector="Button.primary:pointerover /template/ ContentPresenter">
        <Setter Property="Background" Value="#23703a" />
    </Style>
    <Style Selector="TextBox:error">
        <Setter Property="BorderBrush" Value="Firebrick" />
    </Style>
</Window.Styles>

<Button Classes="primary" Content="Confirm order" />

Classes can also be added and removed from code or through bindings (Classes.active="{Binding IsActive}"), a clean way to change the look based on state.

Resources for both themes

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Light">
                <SolidColorBrush x:Key="PanelBackground" Color="#F4F6F8" />
            </ResourceDictionary>
            <ResourceDictionary x:Key="Dark">
                <SolidColorBrush x:Key="PanelBackground" Color="#1E2226" />
            </ResourceDictionary>
        </ResourceDictionary.ThemeDictionaries>
    </ResourceDictionary>
</Application.Resources>

<Border Background="{DynamicResource PanelBackground}" />

ControlTheme

To completely redesign a control you use a ControlTheme, which defines its template and base styles. For small tweaks, selector-based styles are simpler and stay compatible with Fluent theme updates.

Comments (0)

No comments yet.

Leave a comment