Search code examples
c#wpfxamllivecharts

LiveCharts2 binding continuously changing data to graph


I'm new in WPF and C# so go easy on me :) My goal is to plot data to graph using LiveCharts2 with WPF help and add data live.

I followed the example of LiveCharts2 added the class ViewModel with and the XAML and everything worked fine:

    public partial class ViewModel
    {
        public ISeries[] Series { get; set; } =
        {
        new LineSeries<double>
        {
            Values = new double[] { 1, 2 },
            Fill = null
        }
        };

This is static data .. how do I bind it to a variable that changes at any given time? or how should I change the code for that purpose?

I tried to write only XAML code (view code) and took the example from LiveCharts2 to add data to the "Values" but couldn't make it.

I want something like this and just fire and forget & wish that the data plot will update automatically.

        new LineSeries<double>
        {
            Values = new double[] { myChangedata },
            Fill = null
        }

Solution

  • You need to use an ObservableCollection instead of an array so the chart can receive updates.

    public partial class ViewModel
    {
       private ObservableCollection<double> myChangedData = new();
    
       public ViewModel()
       {
          Series.Add(new LineSeries<double>
          {
             Values = myChangedData,
             Fill = null,
          });
       }
    
       public object Sync { get; } = new();
    
       public List<ISeries> Series { get; set; } = new();
    }
    

    Then to add data

    lock (Sync)
    {
       // Any changes including adding, clearing, etc must be synced.
       myChangedData.Add(1D);
       myChangedData.Add(2D);
    }
    

    When doing live data be sure you set the SyncContext property on the chart and always lock it before any changes.

    <lc:CartesianChart Series="{Binding Series}" SyncContext="{Binding Sync}"/>