Category / Section
How to bind array collection to Xamarin.Forms Chart?
1 min read
This article describes how to bind an array collection to chart series. Array collection can be bound to chart series by mapping the array name and its index to the XBindingPath and YBindingPath properties of the series as demonstrated in the following code snippet.
C#
public class Model { public double X { get; set; } public double[] Y { get; set; } } public class ViewModel { public ObservableCollection<Model> Data { get; set; } public ViewModel() { Data = new ObservableCollection<Model>(); Data.Add(new Model { X = 1, Y = new double[] { 4, 10 } }); Data.Add(new Model { X = 2, Y = new double[] { 8, 15 } }); Data.Add(new Model { X = 3, Y = new double[] { 12, 20 } }); Data.Add(new Model { X = 4, Y = new double[] { 16, 25 } }); } }
XAML
<chart:SfChart> … <chart:SfChart.BindingContext> <local:ViewModel/> </chart:SfChart.BindingContext> <chart:SfChart.Series> <chart:ColumnSeries x:Name="ChartSeries" ItemsSource="{Binding Data}" XBindingPath="X" YBindingPath="Y[0]"/> </chart:SfChart.Series> </chart:SfChart>
C#
ColumnSeries series = new ColumnSeries() { XBindingPath = "X", YBindingPath = "Y[0]", ItemsSource = new ViewModel().Data }; ChartControl.Series.Add(series);
Output