Data-Binding
This section describes data binding.
The steps required to create data bound charts are identical to the ones we mentioned in the earlier topics
1. Choose the chart type (ChartType property).
2. Set up the axes (AxisX and AxisY properties).
3. Add one or more data series (Children collection).
4. Adjust the chart's appearance using the Theme and Palette properties.
The only difference is in step 3. When you create data-bound charts, you need to set the ItemsSource property to the collection of items that contain the data you want to chart. Then, use the dataSeries.ValueBinding property to specify which property of the items contains the values to be plotted.
For example, here is the code we used before to generate the Sales Per Region chart (not data-bound):
// Get the data
var data = GetSalesPerRegionData();
// Show regions along label axis
_c1Chart.Data.ItemNames = (
from r in data
select r.Region).ToArray();
// Add Revenue series
var ds = new DataSeries();
ds.Label = "Revenue";
ds.ValuesSource = (from r in data select r.Revenue).ToArray();
_c1Chart.Data.Children.Add(ds);
// Add Expense series
ds = new DataSeries();
ds.Label = "Expense";
ds.ValuesSource = (from r in data select r.Expense).ToArray();
_c1Chart.Data.Children.Add(ds);
// Add Profit series
ds = new DataSeries();
ds.Label = "Profit";
ds.ValuesSource = (from r in data select r.Profit).ToArray();
_c1Chart.Data.Children.Add(ds);
Here is the data-bound version of the code. The result is identical:
// Get the data
var data = GetSalesPerRegionData();
_c1Chart.Data.ItemsSource = data;
// Show regions along label axis
_c1Chart.Data.ItemNameBinding = new Binding("Region");
// Add data series
foreach (string series in "Revenue,Expense,Profit".Split(','))
{
var ds = new DataSeries();
ds.Label = series;
ds.ValueBinding = new Binding(series);
_c1Chart.Data.Children.Add(ds);
}
The data-bound version of the code is even more compact than the original. The three series are created in a loop, taking advantage of the fact that the names of the properties we want to chart are the same as the names we want to use for each data series.
You can assign any object that implements the IEnumerable interface to the ItemsSource property. This includes simple lists as shown above, LINQ queries, and DataTable objects provided by the C1.Silverlight.Data assembly.