Skip to content

Custom Interaction

H.P. Gansevoort edited this page Nov 27, 2026 · 1 revision

Custom Interaction

A native chart control (WPF, Avalonia, Uno or MAUI, and their streaming controls) hands every pointer, wheel and key event to a controller. By default that is the built-in InteractionController with fifteen gestures (the table on Interactive Controls), and a control you leave alone behaves that way. The control's ControllerFactory lets you change it in three steps, each going further than the one before:

  1. Choose the built-in gestures: take one out, move one or switch one off and on again.
  2. Write a gesture of your own and put it in the list, beside the built-in ones or in the place of one.
  3. Write a controller of your own, around the built-in one or from nothing.

The examples use the Avalonia control; the WPF and Uno controls and the MAUI view have the same ControllerFactory.

How a controller is made

For every figure it shows, the control makes an InteractionContext and calls its ControllerFactory with it. The context holds what a controller needs:

Member What it is
Figure the figure on screen
ChartId the chart the events are addressed to (empty when the figure has none)
Layout the layout of the latest paint: where each plot area is and the range it shows; a repaint replaces what it reads, so a drag carries on
Sink where every event goes: it changes the figure (or sends the event to a server), raises the control's DataPointClicked for a click on a point, and tells the control's ChartEventHandler
Toolbar which drawing tool is active, for the trendline, level and Fibonacci gestures
UpdateLayout(layout) hands the context the layout of a new paint

The default factory is InteractionController.Create. Setting ControllerFactory again makes a new controller from the next paint: a gesture in progress ends, and Home still goes back to the view the figure remembers.

1. Choose the built-in gestures

InteractionController.DefaultModifiers(context) returns the fifteen gestures as a List<InteractionModifier>, in the order they claim an event: the first whose Handles* answers yes takes the press, the wheel turn or the key. Edit the list and make the controller from it with InteractionController.Create(context, modifiers). The controller keeps a copy, so the list is yours again afterwards.

This chart has no legend toggle and no Delete key for drawings, and a checkbox switches the rectangle zoom off and on:

using MatPlotLibNet;
using MatPlotLibNet.Avalonia;
using MatPlotLibNet.Interaction;

var chart = new MplChartControl
{
    Figure = Plt.Create().Plot([1.0, 2, 3], [2.0, 4, 3]).Build(),
    IsInteractive = true,
};
bool rectangleZoom = true;

chart.ControllerFactory = context =>
{
    var modifiers = InteractionController.DefaultModifiers(context);
    modifiers.RemoveAll(m => m is LegendToggleModifier or DrawingToolSelectionModifier);
    if (!rectangleZoom)
        modifiers.RemoveAll(m => m is RectangleZoomModifier);
    return InteractionController.Create(context, modifiers);
};

// When the checkbox changes: set the switch and hand the control its factory again, so the next paint makes a new controller.
rectangleZoom = false;
chart.ControllerFactory = chart.ControllerFactory;

The double-click, Home and Escape reset is HomeModifier, the wheel zoom ZoomModifier, a plain drag PanModifier; every type is in the table on Interactive Controls.

2. A gesture of your own

A gesture derives from InteractionModifier and is made from the context's ChartId, Layout and Sink. It claims an event by overriding HandlesPointerPressed, HandlesScroll or HandlesKeyDown (all answer no until you override them), acts on it in OnPointerPressed, OnPointerMoved, OnPointerReleased, OnScroll or OnKeyDown, and sends what happened with Emit. Layout turns a pixel into data (HitTestAxes, PixelToData, GetDataRange), and the events of the library (ZoomEvent, PanEvent, ResetEvent and the others) change the figure when the sink applies them.

This one zooms only the X axis when the wheel turns over a plot, and stands in the place of the built-in wheel zoom:

using MatPlotLibNet;
using MatPlotLibNet.Avalonia;
using MatPlotLibNet.Interaction;

var chart = new MplChartControl
{
    Figure = Plt.Create().Plot([1.0, 2, 3, 4], [2.0, 4, 3, 5]).Build(),
    IsInteractive = true,
};

chart.ControllerFactory = context =>
{
    var modifiers = InteractionController.DefaultModifiers(context);
    modifiers[modifiers.FindIndex(m => m is ZoomModifier)] = new HorizontalZoom(context);
    return InteractionController.Create(context, modifiers);
};

/// <summary>Zooms the X axis about the pointer when the wheel turns over a plot; the Y axis keeps its range.</summary>
sealed class HorizontalZoom(InteractionContext context) : InteractionModifier(context.ChartId, context.Layout, context.Sink)
{
    public override bool HandlesScroll(ScrollInputArgs args) => Layout.HitTestAxes(args.X, args.Y) is not null;

    public override void OnScroll(ScrollInputArgs args)
    {
        int axes = Layout.HitTestAxes(args.X, args.Y)!.Value;
        var range = Layout.GetDataRange(axes);
        double x = Layout.PixelToData(args.X, args.Y, axes)!.Value.DataX;
        double scale = args.DeltaY < 0 ? 0.85 : 1 / 0.85;   // in when the wheel turns up

        Emit(new ZoomEvent(ChartId, axes, x - (x - range.XMin) * scale, x + (range.XMax - x) * scale, range.YMin, range.YMax));
    }
}

Put a gesture where it should win: one earlier in the list claims an event before the ones after it. A gesture that claims nothing can still follow the pointer and show something, the way the crosshair and the hover do, by overriding these members of InteractionModifier; the controller asks every gesture for them:

Member When the controller asks
OnPointerTracked(args) on every move of the pointer, unless this gesture is the one being dragged (that one is told through OnPointerMoved)
ActiveTooltip for the control's tooltip: the first gesture that has one wins (the built-in one is the hover's)
ActiveBrushSelect for the rubber band the control draws while a gesture drags one
ActiveCrosshair for the crosshair a control or an app draws

3. A controller of your own

A controller implements IInteractionController: the five Handle* methods the control forwards its input to, the three Active* properties it draws from, UpdateLayout, and the InvalidateRequested event it raises to be painted again for something that is not a change to the figure (the rubber band of a drag). Whatever it sends goes into context.Sink, so a click on a point still raises the control's DataPointClicked and the control's ChartEventHandler is still told of every event, and a change to the figure is painted without the controller asking.

The shortest way is around the built-in controller. This one lets the wheel through only while Ctrl is held, so a chart on a page that scrolls does not take the turn of the wheel meant for the page, and leaves everything else to the built-in gestures:

using MatPlotLibNet;
using MatPlotLibNet.Avalonia;
using MatPlotLibNet.Interaction;

var chart = new MplChartControl
{
    Figure = Plt.Create().Plot([1.0, 2, 3], [2.0, 4, 3]).Build(),
    IsInteractive = true,
};

chart.ControllerFactory = context => new ZoomWithCtrl(InteractionController.Create(context));

/// <summary>The built-in controller, except that the wheel zooms only while Ctrl is held.</summary>
sealed class ZoomWithCtrl(IInteractionController inner) : IInteractionController
{
    public event Action? InvalidateRequested
    {
        add => inner.InvalidateRequested += value;
        remove => inner.InvalidateRequested -= value;
    }

    public void HandleScroll(ScrollInputArgs args)
    {
        if ((args.Modifiers & ModifierKeys.Ctrl) != 0)
            inner.HandleScroll(args);
    }

    public void HandlePointerPressed(PointerInputArgs args) => inner.HandlePointerPressed(args);
    public void HandlePointerMoved(PointerInputArgs args) => inner.HandlePointerMoved(args);
    public void HandlePointerReleased(PointerInputArgs args) => inner.HandlePointerReleased(args);
    public void HandleKeyDown(KeyInputArgs args) => inner.HandleKeyDown(args);
    public BrushSelectState? ActiveBrushSelect => inner.ActiveBrushSelect;
    public HoverTooltipContent? ActiveTooltip => inner.ActiveTooltip;
    public CrosshairState? ActiveCrosshair => inner.ActiveCrosshair;
    public void UpdateLayout(IChartLayout layout) => inner.UpdateLayout(layout);
}

A controller written from nothing does the same with its own logic: it reads pixels through context.Layout, sends its events into context.Sink, and in UpdateLayout calls context.UpdateLayout(layout) so that what reads context.Layout (its own code, and any built-in gesture it uses) sees the latest paint.

Trying it without a window

InteractionContext has a public constructor that takes the figure, a layout and the sink, so a gesture or a controller can be driven from a test or a console program: build the layout with ChartLayout.Create(figure, plotAreas), call the Handle* methods with the pixel you want, and look at what reached the sink or the figure. The 1.31.0 example on Examples does that.

MatPlotLibNet 1.31.0

On the docs site

Clone this wiki locally