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.
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.
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);
}
}
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:
- Guard the range. All values equal means division by zero;
Math.Max(1e-9, …)keeps the line flat instead ofNaN. - Inset by the stroke width. A 2px pen centred on the edge clips half of itself.
- Use
Bounds, notDesiredSize. The control is arranged beforeRender.
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.
Renderruns often; it must be cheap and side-effect free.
Try it
- Add a filled area under the line: build the same geometry, close it to the baseline, and fill before stroking.
- Draw a faint grid using
context.DrawLinewith a 1px pen. - Add a
PointerMovedhandler 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.cssrc/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.