I am currently working with Livecharts and I am trying to bind a SeriesCollection to a DataGrid. It is possible to bind it, but this series have some values and I want the DataGrid to show those point. However it only shows that two SeriesCollection items are binded LiveCharts.SeriesAlgorithm.LineAlgorithm, I do not know if a converter is needed to solve this problem.
xaml.cs
public MyConstructor()
{
SeriesCollection = new SeriesCollection();
SeriesCollection.Add(reducedValuesLineSeries); // adds some points
SeriesCollection.Add(fullValuesLineSeries); // adds a line composed by many ponits
}
private SeriesCollection seriesCollection;
public SeriesCollection SeriesCollection
{
get => seriesCollection;
set
{
seriesCollection = value;
OnPropertyChanged();
}
}
xaml
<DataGrid ItemsSource="{Binding SeriesCollection}"/>
You have to implement a IValueConverter
to extract those points from the series. Apparently the points are buried deep inside the "collection". The name collection is quite misleading here as SeriesCollection
is more a data model than an actual collection. The whole library is implemented quite confused.
What data type you have actually as your data points depends on your implementation. Sadly, you are not showing these details.
This example assumes the data item to be of type Point
:
ViewModel.cs
class ViewModel
{
public ViewModel()
{
var chartValues = new ChartValues<Point>();
// Create a sine
for (int x = 0; x < 361; x++)
{
var point = new Point() {X = x, Y = Math.Sin(x * Math.PI / 180)};
chartValues.Add(point);
}
this.SeriesCollection = new SeriesCollection
{
new LineSeries
{
Configuration = new CartesianMapper<Point>()
.X(point => point.X)
.Y(point => point.Y),
Title = "Series X",
Values = chartValues,
Fill = Brushes.DarkRed
}
};
}
}
SeriesCollectionToPointsConverter.cs
class SeriesCollectionToPointsConverter : IValueConverter
{
#region Implementation of IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
value is SeriesCollection seriesCollection
? seriesCollection.SelectMany(series => series.Values as ChartValues<Point>)
: Binding.DoNothing;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
throw new NotSupportedException();
#endregion
}
MainWindow.xaml
<Window>
<Window.DataContext>
<ViewModel />
</Window.DataContext>
<Window.Resources>
<SeriesCollectionToPointsConverter x:Key="SeriesCollectionToPointsConverter" />
</Window.Resources>
<DataGrid ItemsSource="{Binding SeriesCollection, Converter={StaticResource SeriesCollectionToPointsConverter}}" />
</Window>