Search code examples
c#wpflivecharts

How can I update the chart in livechart based on array value with a button?


i am currently using Livechart, Cartesian chart for my WPF c# program, based on the example given in the livecharts website. I have successfully manage to represent the value of the array onto the Cartesian Chart.

Below is the xaml code

  <Grid Margin="0,0,219.4,-0.2">
                        <lvc:CartesianChart x:Name="cartchartdb" Series="{Binding SeriesCollection}" LegendLocation="Right" >
                            <lvc:CartesianChart.AxisY>
                                <lvc:Axis Title="Value" LabelFormatter="{Binding YFormatter}"></lvc:Axis>
                            </lvc:CartesianChart.AxisY>
                            <lvc:CartesianChart.AxisX>
                                <lvc:Axis Title="Date" Labels="{Binding Labels}"></lvc:Axis>
                            </lvc:CartesianChart.AxisX>
                        </lvc:CartesianChart>
                    </Grid>

Below is the code. for the Xaml.cs

 private void cartchartinit()
    {

        SeriesCollection = new SeriesCollection
        {
            new LineSeries
            {
                Title = "Avg Speed (KM/H)",
                Values = arrayspeedavg.AsChartValues()
            },
            new LineSeries
            {
                Title = "Avg Gap (Metre)",
                Values = arraygapavg.AsChartValues()                                                     
            },
            
        };

        Labels = datearray;
        YFormatter = value => value.ToString("");        
       
        DataContext = this;
        cartchartdb.Update(true);
    }

The problem now is I was not able to update the graph again when a new value is inserted into the array.*edit: The chart will only update if i restart the program.

My current idea is to put a button to refresh the chart but it didnt update.

Code for button update:

        private void refreshcart_Click(object sender, RoutedEventArgs e)
    {
        getvalueforgraphing();

        cartchartdb.Update(true);
    }

the getvalueforgraphing() is the function to update the array back with the new value inserted. The cartchartdb is the name for the lvc.CartesianChart tool.

Hope someone could help me with this.


Solution

  • Ok nvm got it!

    basically my workaround is as shown below

            private void refreshcart_Click(object sender, RoutedEventArgs e)
        {
            getvalueforgraphing();
    
           // SeriesCollection[0].Values.Clear();
            SeriesCollection[0].Values = arrayspeedavg.AsChartValues();
            SeriesCollection[1].Values = arraygapavg.AsChartValues();
            Labels = datearray;
    
        }