Add Point On Click
This sample uses C# 13 preview features such as partial properties, it also uses features from the CommunityToolkit.Mvvm package, you can learn more about it here.
View model
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.Input;
using LiveChartsCore.Defaults;
using LiveChartsCore.Kernel.Events;
using LiveChartsCore.Kernel.Sketches;
namespace ViewModelsSamples.Events.AddPointOnClick;
public partial class ViewModel
{
public ObservableCollection<ObservablePoint> Points { get; set; } =
[
new(0, 5),
new(3, 8),
new(7, 9)
];
[RelayCommand]
public void PointerDown(PointerCommandArgs args)
{
var chart = (ICartesianChartView)args.Chart;
// scales the UI coordinates to the corresponding data in the chart.
var scaledPoint = chart.ScalePixelsToData(args.PointerPosition);
// finally add the new point to the data in our chart.
Points.Add(new ObservablePoint(scaledPoint.X, scaledPoint.Y));
}
}
XAML
<UserControl
x:Class="AvaloniaSample.Events.AddPointOnClick.View"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lvc="using:LiveChartsCore.SkiaSharpView.Avalonia"
xmlns:vms="using:ViewModelsSamples.Events.AddPointOnClick"
x:DataType="vms:ViewModel">
<UserControl.DataContext>
<vms:ViewModel/>
</UserControl.DataContext>
<lvc:CartesianChart
PointerPressedCommand="{Binding PointerDownCommand}"
TooltipPosition="Hidden">
<lvc:CartesianChart.Series>
<lvc:XamlLineSeries
Values="{Binding Points}"
Fill="{x:Null}"
DataPadding="{lvc:Point '5,5'}"/>
</lvc:CartesianChart.Series>
</lvc:CartesianChart>
</UserControl>