Add Point On Click

sample image

View model

using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using LiveChartsCore;
using LiveChartsCore.Defaults;
using LiveChartsCore.SkiaSharpView;

namespace ViewModelsSamples.Events.AddPointOnClick;

[ObservableObject]
public partial class ViewModel
{
    public ViewModel()
    {
        var data = new ObservableCollection<ObservablePoint>
        {
            new(0, 5),
            new(3, 8),
            new(7, 9)
        };

        Data = data;

        SeriesCollection = new ISeries[]
        {
            new LineSeries<ObservablePoint>
            {
                Values = data,
                Fill = null,
                DataPadding = new LiveChartsCore.Drawing.LvcPoint(5, 5)
            }
        };
    }

    public ObservableCollection<ObservablePoint> Data { get; set; }

    public ISeries[] SeriesCollection { get; set; }
}

HTML

@page "/Events/AddPointOnClick"
@using LiveChartsCore.Defaults
@using LiveChartsCore.Drawing
@using LiveChartsCore.SkiaSharpView.Blazor
@using ViewModelsSamples.Events.AddPointOnClick

<CartesianChart
	@ref="_chart"
	Series="ViewModel.SeriesCollection"
	OnPointerDownCallback="onPointerDown"
	TooltipPosition="LiveChartsCore.Measure.TooltipPosition.Hidden">
</CartesianChart>

@code {
    private CartesianChart _chart;

    public ViewModel ViewModel { get; set; } = new();

    private void onPointerDown(PointerEventArgs e)
    {
        var p = new LvcPointD(e.OffsetX, e.OffsetY);

        // scales the UI coordinates to the corresponding data in the chart.
        var dataCoordinates = _chart.ScalePixelsToData(p);

        // finally add the new point to the data in our chart.
        ViewModel?.Data.Add(new ObservablePoint(dataCoordinates.X, dataCoordinates.Y));

        // You can also get all the points or visual elements in a given location.
        var points = _chart.GetPointsAt(new LvcPoint(p.X, p.Y));
        var visuals = _chart.GetVisualsAt(new LvcPoint(p.X, p.Y));
	}
}