Add Point On Click
The [ObservableObject]
, [ObservableProperty]
and [RelayCommand]
attributes come from the
CommunityToolkit.Mvvm package, you can read more about it
here.
View model
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using LiveChartsCore;
using LiveChartsCore.Defaults;
using LiveChartsCore.Kernel.Events;
using LiveChartsCore.Kernel.Sketches;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.Drawing;
namespace ViewModelsSamples.Events.AddPointOnClick;
public partial class ViewModel : ObservableObject
{
public ISeries[] SeriesCollection { get; set; } =
new ISeries[]
{
new LineSeries<ObservablePoint>
{
Values = new ObservableCollection<ObservablePoint>
{
new(0, 5),
new(3, 8),
new(7, 9)
},
Fill = null,
DataPadding = new LiveChartsCore.Drawing.LvcPoint(5, 5)
}
};
[RelayCommand]
public void PointerDown(PointerCommandArgs args)
{
var chart = (ICartesianChartView<SkiaSharpDrawingContext>)args.Chart;
var values = (ObservableCollection<ObservablePoint>)SeriesCollection[0].Values!;
// 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.
values.Add(new ObservablePoint(scaledPoint.X, scaledPoint.Y));
}
}
XAML
<UserControl
x:Class="UnoWinUISample.Events.AddPointOnClick.View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:lvc="using:LiveChartsCore.SkiaSharpView.WinUI"
xmlns:vms="using:ViewModelsSamples.Events.AddPointOnClick"
mc:Ignorable="d">
<UserControl.DataContext>
<vms:ViewModel/>
</UserControl.DataContext>
<lvc:CartesianChart
x:Name="chart"
Series="{Binding SeriesCollection}"
PointerPressedCommand="{Binding PointerDownCommand}"
TooltipPosition="Hidden">
</lvc:CartesianChart>
</UserControl>
View code behind
using LiveChartsCore.Defaults;
using LiveChartsCore.Drawing;
using ViewModelsSamples.Events.AddPointOnClick;
using Microsoft.UI.Xaml.Controls;
namespace UnoWinUISample.Events.AddPointOnClick;
public sealed partial class View : UserControl
{
public View()
{
InitializeComponent();
}
}