Avalonia Field Guide
About

Module 3 · Lesson 11 of 16

A control with a contract, not a copy

A TemplatedControl publishes properties and behaviour; a ControlTheme owns the pixels. One theme edit restyles every pill in the app.

30 minHeadless-tested

UserControl is the right tool for a page. It is the wrong tool for a reusable element: its XAML is its appearance, so every instance looks the same and nothing can restyle it.

src/CourseApp/Controls/Pill.cs
using Avalonia;
using Avalonia.Controls.Primitives;

namespace CourseApp.Controls;

/// <summary>
/// A templated control: behavior and properties live in C#, appearance lives in a
/// ControlTheme. This is the difference between "a UserControl I copied" and a
/// control the rest of the app can style.
/// </summary>
public class Pill : TemplatedControl
{
    public static readonly StyledProperty<string> TextProperty =
        AvaloniaProperty.Register<Pill, string>(nameof(Text), "");

    public static readonly StyledProperty<bool> IsAccentProperty =
        AvaloniaProperty.Register<Pill, bool>(nameof(IsAccent));

    public string Text
    {
        get => GetValue(TextProperty);
        set => SetValue(TextProperty, value);
    }

    public bool IsAccent
    {
        get => GetValue(IsAccentProperty);
        set => SetValue(IsAccentProperty, value);
    }
}
Screenshot of the custom-control lesson sample
The lesson's sample, rendered headlessly at 1280×800. Light and dark are both captured.

The contract

A TemplatedControl declares styled properties and raises changes. It has no visual tree of its own. Text and IsAccent are the entire public surface of this control, and both participate in styling, binding, and animation like any built-in property.

public static readonly StyledProperty<bool> IsAccentProperty =
    AvaloniaProperty.Register<Pill, bool>(nameof(IsAccent));

That AvaloniaProperty.Register line is not boilerplate to skip. It is what makes the property inheritable, bindable, and visible to the styling system.

The theme

src/CourseApp/Theme/Controls.axaml
<ResourceDictionary xmlns="https://github.com/avaloniaui"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:controls="using:CourseApp.Controls">

    <ControlTheme x:Key="{x:Type controls:Pill}" TargetType="controls:Pill">
        <Setter Property="Background" Value="{DynamicResource SurfaceMuted}" />
        <Setter Property="Foreground" Value="{DynamicResource Ink}" />
        <Setter Property="Padding" Value="10,4" />
        <Setter Property="Template">
            <ControlTemplate>
                <Border Background="{TemplateBinding Background}"
                        CornerRadius="20"
                        Padding="{TemplateBinding Padding}">
                    <TextBlock Text="{TemplateBinding Text}"
                               Foreground="{TemplateBinding Foreground}"
                               FontSize="12"
                               FontWeight="SemiBold" />
                </Border>
            </ControlTemplate>
        </Setter>

        <Style Selector="^[IsAccent=True]">
            <Setter Property="Background" Value="{DynamicResource Accent}" />
            <Setter Property="Foreground" Value="#FFFFFF" />
        </Style>
    </ControlTheme>
</ResourceDictionary>

The x:Key="{x:Type controls:Pill}" is the convention: a type-keyed ControlTheme is found automatically by every Pill in the app. Inside:

  • Template is the only visual structure.
  • {TemplateBinding Text} pulls the control's property into the template. Use TemplateBinding for one-way reads; {Binding $parent[controls:Pill].Text} when you need two-way.
  • Selector="^[IsAccent=True]" is a nested style inside the theme. ^ means "this control". It applies the accent brushes without any code.

The most common mistake is putting x:Key on the theme and expecting magic. Controls only find a type-keyed theme automatically; a keyed one must be referenced with Theme="{StaticResource MyPillTheme}".

Where do I put the C#?

One file per control, next to its theme is fine for a small app:

Controls/Pill.cs
Theme/Controls.axaml

For a library, split Themes/Generic.axaml and merge it from App.axaml. For a product, group by feature (Features/Billing/PriceTag.cs).

Try it

  1. Add a Size property (Small, Medium) and a nested style for each value.
  2. Add a PointerOver pseudo-class state: brighten the border when :pointerover is active.
  3. Move the Pill theme into a separate assembly and reference it with avares://. This is how you would ship a design system.

Next: when a template isn't the answer.

Files this lesson draws from

  • src/CourseApp/Controls/Pill.cs
  • src/CourseApp/Theme/Controls.axaml
  • src/CourseApp/Lessons/10_Control/ControlView.axaml

VerifiedThe verifier creates a Pill with IsAccent set, hosts it in a window, and asserts the ControlTheme's template produced a TextBlock with the expected text.

Back to top