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="WPFSample.Events.AddPointOnClick.View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lvc="clr-namespace:LiveChartsCore.SkiaSharpView.WPF;assembly=LiveChartsCore.SkiaSharpView.WPF"
xmlns:vms="clr-namespace:ViewModelsSamples.Events.AddPointOnClick;assembly=ViewModelsSamples">
<UserControl.DataContext>
<vms:ViewModel/>
</UserControl.DataContext>
<lvc:CartesianChart
PointerPressedCommand="{Binding PointerDownCommand}"
TooltipPosition="Hidden">
<lvc:CartesianChart.Series>
<lvc:SeriesCollection>
<lvc:XamlLineSeries
Values="{Binding Points}"
Fill="{x:Null}"
DataPadding="5,5"/>
</lvc:SeriesCollection>
</lvc:CartesianChart.Series>
</lvc:CartesianChart>
</UserControl>