Binding a collection of series to a XamDataChart

Kiril Matev / Monday, August 23, 2010

Let’s say you have a collection of data series you need to bind to a XamDataChart, our fast and user-friendly charting control in WPF and Silverlight. Declare the series in the XAML code, you say. However, let’s assume we don’t know the exact number of series we will be getting in our collection. So, how do you do that?

Basically, you need to cycle through all the series view models you have in your collection in code-behind, initialize a series, and add it to the chart for each series. It has been built using Visual Studio 2010 and references libraries from our WPF Data Visualization product. Please download a trial version here.

The approach is shown below – TickerBuffer is the class containing a collection of data items to be bound to the chart, while seriesList is a List of instances of TickerBuffer.

int seriesIndex = 1;
//go through all the buffers in the list, generating a series for each one
foreach (TickerBuffer seriesData in seriesList)
    LineSeries lineSeries = new LineSeries();
    //set the axes
    lineSeries.XAxis = (CategoryXAxis)this.chart.Axes.First((axis) => axis.Name == "xAxis");
    lineSeries.YAxis = (NumericYAxis)this.chart.Axes.First((axis) => axis.Name == "yAxis");

    //set the legend
    lineSeries.Legend = Legend;
    //set the itemsource of the X-axis
    lineSeries.XAxis.ItemsSource = seriesData;

    //set the itemsource of the series itself
    lineSeries.ItemsSource = seriesData;
    lineSeries.ValueMemberPath = "Column2";

    //set title
    lineSeries.Title = "Series" + seriesIndex.ToString();

    //insert series
    chart.Series.Insert(0, lineSeries);

Please note how we setup a new series to reference the axis and legend elements we have defined in XAML, before finally adding the newly instantiated series to the Series collection of the XamDataChart instance.

Following this simple approach you can easily generate charts on the fly and effectively handle a varying number of series. This will help you quickly take advantage of the advanced features the XamDataChart offers, and help your customers view data with ease.

If you have any questions, do not hesitate to email me at