'How to use ObservableCollection with LiveChart2
How to use ObservableCollection with LiveCharts2
I am trying to implement LiveChart2 using ObservableCollection to update the chart everytime a new value is added. The chart works fine if I add all the data at once but I am stuck in implementing "ObservableCollection". Link to doc: https://github.com/beto-rodriguez/LiveCharts2/blob/master/docs/overview/1.4.automatic%20updates.md I need help please. I have this code:
using System.Collections.ObjectModel;
using System.Windows;
using LiveChartsCore;
using LiveChartsCore.Defaults;
using LiveChartsCore.SkiaSharpView;
namespace WpfSample
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public ISeries[] Series { get; set; }
public ObservableCollection<ObservableValue> Series2 { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
// This one is not working ///////////////////////////////////
Series2 = new ObservableCollection<ObservableValue>();
Series2.Add(new ObservableValue { Value = 1 });
Series2.Add(new ObservableValue { Value = 2 });
Series2.Add(new ObservableValue { Value = 3 });
// every time you update the Value property, you will also see that change in the user interface
Series2[0].Value = 5;
// This one is working fine
Series = new ISeries[]
{
new LineSeries<double>
{
Values = new double[] { 6, 4, 3, 9, 4, 2, 1 },
}
};
DataContext = this;
}
}
}
<Window x:Class="WpfSample.MainWindow"
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:local="clr-namespace:WpfSample"
xmlns:lvc="clr-namespace:LiveChartsCore.SkiaSharpView.WPF;assembly=LiveChartsCore.SkiaSharpView.WPF"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<lvc:CartesianChart
Series="{Binding Series}" Margin="4,4,433,174">
</lvc:CartesianChart>
<lvc:CartesianChart
Series="{Binding Series2}" Margin="403,0,0,177">
</lvc:CartesianChart>
<Button Content="Button" HorizontalAlignment="Left" Margin="728,318,0,0" VerticalAlignment="Top" Click="Button_Click"/>
</Grid>
</Window>
Solution 1:[1]
Maybe try something like this:
public ObservableCollection<ISeries> Series2 { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
Series2 = new ObservableCollection<ISeries>();
Series2.Add(new LineSeries<double> { Values = new List<double> {1,2,3 } });
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |