Avalonia Field Guide
About

Module 3 · Lesson 12 of 16

When a template isn't the answer

Geometry belongs in Render, not in a tree of borders. AffectsRender ties the drawing to the data.

30 minHeadless-tested

You can build a chart out of Borders and RotateTransforms. You should not. Every one of those borders is a layout participant, a hit-test target, and a style lookup, and the result is slow and imprecise.

src/CourseApp/Controls/Sparkline.cs
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;

namespace CourseApp.Controls;

/// <summary>
/// A control that owns its pixels. Render() is the whole API: no template, no
/// children, no XAML — just geometry drawn into the DrawingContext.
/// </summary>
public sealed class Sparkline : Control
{
    public static readonly StyledProperty<IReadOnlyList<double>> PointsProperty =
        AvaloniaProperty.Register<Sparkline, IReadOnlyList<double>>(nameof(Points), []);

    public static readonly StyledProperty<IBrush?> StrokeProperty =
        AvaloniaProperty.Register<Sparkline, IBrush?>(nameof(Stroke));

    public static readonly StyledProperty<double> StrokeThicknessProperty =
        AvaloniaProperty.Register<Sparkline, double>(nameof(StrokeThickness), 2);

    static Sparkline() =>
        AffectsRender<Sparkline>(PointsProperty, StrokeProperty, StrokeThicknessProperty);

    public IReadOnlyList<double> Points
    {
        get => GetValue(PointsProperty);
        set => SetValue(PointsProperty, value);
    }

    public IBrush? Stroke
    {
        get => GetValue(StrokeProperty);
        set => SetValue(StrokeProperty, value);
    }

    public double StrokeThickness
    {
        get => GetValue(StrokeThicknessProperty);
        set => SetValue(StrokeThicknessProperty, value);
    }

    public override void Render(DrawingContext context)
    {
        var bounds = Bounds;
        var points = Points;

        if (bounds.Width <= 0 || bounds.Height <= 0 || points.Count < 2)
            return;

        var min = double.MaxValue;
        var max = double.MinValue;
        foreach (var point in points)
        {
            min = Math.Min(min, point);
            max = Math.Max(max, point);
        }

        var range = Math.Max(1e-9, max - min);
        var padding = 6.0;
        var width = bounds.Width - (padding * 2);
        var height = bounds.Height - (padding * 2);

        var geometry = new StreamGeometry();
        using (var sink = geometry.Open())
        {
            for (var i = 0; i < points.Count; i++)
            {
                var x = padding + (i * width / (points.Count - 1));
                var y = bounds.Height - padding - ((points[i] - min) / range * height);
                var point = new Point(x, y);

                if (i == 0)
                    sink.BeginFigure(point, isFilled: false);
                else
                    sink.LineTo(point);
            }

            sink.EndFigure(isClosed: false);
        }

        var pen = new Pen(Stroke ?? Brushes.OrangeRed, StrokeThickness, lineCap: PenLineCap.Round);
        context.DrawGeometry(null, pen, geometry);
    }
}
Screenshot of the drawing lesson sample
The lesson's sample, rendered headlessly at 1280×800. Light and dark are both captured.

Render is the whole API

Render(DrawingContext) is called when the control needs pixels. You get the control's Bounds and a context that accepts geometry, text, images, and brushes. No children, no template, no layout pass per data point.

static Sparkline() =>
    AffectsRender<Sparkline>(PointsProperty, StrokeProperty, StrokeThicknessProperty);

AffectsRender registers the properties that require a repaint. Change Points and the control invalidates itself; you never call InvalidateVisual() by hand from the view model.

Coordinates are your problem now

The sample maps data values into the control's bounds:

var y = bounds.Height - padding - ((points[i] - min) / range * height);

Three things to get right, every time:

  1. Guard the range. All values equal means division by zero; Math.Max(1e-9, …) keeps the line flat instead of NaN.
  2. Inset by the stroke width. A 2px pen centred on the edge clips half of itself.
  3. Use Bounds, not DesiredSize. The control is arranged before Render.

When to use which

You need Reach for
A composed, stylable element TemplatedControl + ControlTheme
A page assembled from controls UserControl
A chart, gauge, canvas, or custom cursor Control.Render
Thousands of items Virtualized ItemsControl, not drawing

Do not put business logic in Render. Compute the points in the view model or a plain class and pass them in. Render runs often; it must be cheap and side-effect free.

Try it

  1. Add a filled area under the line: build the same geometry, close it to the baseline, and fill before stroking.
  2. Draw a faint grid using context.DrawLine with a 1px pen.
  3. Add a PointerMoved handler that reports the nearest point's value, and prove it with an assertion.

Next: proof, not vibes.

Files this lesson draws from

  • src/CourseApp/Controls/Sparkline.cs
  • src/CourseApp/Lessons/11_Drawing/DrawingView.axaml

VerifiedThe verifier hosts the page, finds both sparklines in the visual tree, and asserts each received data and a non-zero width before the frame is captured.

Back to top