Page view counter

Graphing – Silverlight Toolkit

Okay, thus begins random excursions into aspects of the Silverlight Toolkit, supplementing a more systematic set of videos….

The first thing you need to know about the Silverlight Toolkit is that there are two greatly under-utilized resources available: The Silverlight Toolkit home on Codeplex (where you can get the source and samples) and the dedicated Silverlight Toolkit Controls forum on Silverlight.net (forum 35).

Today I'd like to start looking at some of the graphs. 

One thing you immediately notice when you look at all the graphs at once, is that there is a good deal of commonality in how most work: they want a set of data that can be identified as the IndependentValue and the DependentValue (more on this in a moment) and they want the ItemSource that supplies these values. They would like a title and  most take a width and a height and a name.

Yes, there's a good bit more, but you can go pretty far with that.

Independent vs Dependent Value

Without getting into the technical definition of these terms at all, you can quickly see by looking at the graphs, that the IndependentValues  (IVs) are the names of the things you want to measure,  while the DependentValues (DVs) are the numeric quantities for each of the IVs (this is not a precise definition but a good enough working one.)

You see this immediately when you look at a column series

DVIV

In this graph, Activity is the independent value and Time is the dependent value.

You can just as easily re-label this graph with different independent and dependent variables and it will still make sense,

DVIV2

With these new labels we could well be looking at my monthly budget from 1973.

Creating this chart with the Chart Controls is surprisingly easy.  We start by creating the data, which I prefer to delegate to a class; a better analog to getting the data from outside the program (e.g., from a web service),

Thus, I'll add Expense.cs to the project,

using System.Collections.Generic;

namespace SimpleCharts
{
  public class Expense
  {
    public string Name { get; set; }
    public double Value { get; set; }

    public static List<Expense> GetExpenses()
    {
      List<Expense> expenses = new List<Expense>()
      {
        new Expense() { Name = "Rent",   Value = 175.63 },
        new Expense() { Name = "Books",  Value = 102.77 },
        new Expense() { Name = "Food",   Value = 49.33 },
        new Expense() { Name = "Music",  Value = 75 },
        new Expense() { Name = "Else",   Value = 22 }
      };
      return expenses; 
    }
  }
}

This simple class has two public properties and a static method for generating some values.

Creating the Chart in Xaml

In my first version, I'll simply create a column graph in Xaml and then in the code, set a collection of expenses as its itemSource.  Here's the Xaml,

<UserControl x:Class="SimpleCharts.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:controls="clr-namespace:Microsoft.Windows.Controls;
assembly=Microsoft.Windows.Controls" xmlns:charting="clr-namespace:Microsoft.Windows.Controls.DataVisualization.Charting;
assembly=Microsoft.Windows.Controls.DataVisualization" Width="800" Height="500">
    <Grid x:Name="LayoutRoot" Background="White">
    <Grid.RowDefinitions>
      <RowDefinition Height="8*" />
      <RowDefinition Height="2*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="1*" />
      <ColumnDefinition Width="1*" />
    </Grid.ColumnDefinitions>

      <charting:Chart x:Name="Budget" Margin="10">
      <charting:Chart.Series>
        <charting:ColumnSeries 
          Title="1973" 
          IndependentValueBinding="{Binding Name}"
          DependentValueBinding="{Binding Value}" />
      </charting:Chart.Series>
    </charting:Chart>
      
   </Grid>
</UserControl>

Note that we're adding two namespaces that depend on your adding references for the two assemblies from the Toolkit: DataVisualization.dll and Controls.dll.

The Grid is divided into two rows (80/20) and two columns (50/50) though for now we'll use only the upper left corner. The chart is given a name, and then a series, though in this case we'll have only one series: the columns. We set the IV to bind to the Name of each object and the DV to bind to the value of each object. We'll supply the object (through the ItemSource) in code.

Binding Data To the Chart

The code to bind data to this chart is in Page.xaml.cs,

public Page()
{
  InitializeComponent();
  ColumnSeries cs = Budget.Series[0] as ColumnSeries;
  cs.ItemsSource = Expense.GetExpenses();
}

We are reaching into the control we've named Budget and asking for the first member in its series collection, which we know to be of type ColumnSeries. We can then set the ItemSource on that ColumnSeries to what we get back from the static method GetExpenses, which you will remember is a list of Expense objects, each of which has two public properties: Name and Value, which is just what the control is looking for. The result is a graph based on the data,

FirstChart

Adding A Pie Chart

Because all the charts work the same way, adding a pie chart is trivial. We can cut and paste the column chart and just change the name, and the charting series from ColumnSeries to PieSeries. Other than that, there is nothing to change but the Grid.Column.

<charting:Chart x:Name="BudgetAsPieChart" Grid.Column="1" 
      Margin="10">
  <charting:Chart.Series>
    <charting:PieSeries
      Title="1973" 
      IndependentValueBinding="{Binding Name}"
      DependentValueBinding="{Binding Value}" />
  </charting:Chart.Series>
</charting:Chart>

The code to bind the data is also nearly identical,

 

public Page()
{
  InitializeComponent();
  ColumnSeries cs = Budget.Series[0] as ColumnSeries;
  PieSeries ps = BudgetAsPieChart.Series[0] as PieSeries; 
  ps.ItemsSource = cs.ItemsSource = Expense.GetExpenses();
}

This puts the columns in the upper left and the pie in the upper right,

SecondChart

Evolving Data

Finally, to make this slightly more interesting, let's add a second static method to Expense that returns the next year's data, and a button to our page that will cause us to tell the charts to change their ItemSource to the new data. The effect is very gratifying; the charts morph from one year to the next.

Here's the method to add to Expense.cs

 public static List<Expense> GetNewExpenses()
 {
   List<Expense> expenses = new List<Expense>()
   {
     new Expense() { Name = "Rent",   Value = 375.63 },
     new Expense() { Name = "Books",  Value = 102.77 },
     new Expense() { Name = "Food",   Value = 149.33 },
     new Expense() { Name = "Music",  Value = 45 },
     new Expense() { Name = "Else",   Value = 222.56 }
   };
   return expenses;
 }

Here's the change to the Xaml (added just before the closing tag for the Grid).

<Button x:Name="Change" Content="Change" 
    FontSize="18" Width="120" Height="30" 
    Grid.Row="1"/>

And finally, here is the change to Page.xaml.cs,

public partial class Page : UserControl
{
  public Page()
  {
    InitializeComponent();
    ColumnSeries cs = Budget.Series[0] as ColumnSeries;
    PieSeries ps = BudgetAsPieChart.Series[0] as PieSeries; 
    ps.ItemsSource = cs.ItemsSource = Expense.GetExpenses();
    Change.Click += new RoutedEventHandler( Change_Click );
  }

  void Change_Click( object sender, RoutedEventArgs e )
  {
    ColumnSeries cs = Budget.Series[0] as ColumnSeries;
    cs.Title = "1974";
    cs.ItemsSource = Expense.GetNewExpenses();

    PieSeries ps = BudgetAsPieChart.Series[0] as PieSeries;
    ps.Title = "1974";
    ps.ItemsSource = Expense.GetNewExpenses();
  }
}

Charts3

[I apologize for the color corruption caused by the gif file]

Cross Platform

Finally, we can open the application on the Mac, and see the same charts, behaving the same way and looking exactly as if they belong on the Mac,

ChartsOnMac

Published 24 November 2008 06:00 PM by jesseliberty
Filed under: , ,

Comments

# heuertk said on 24 November, 2008 08:53 PM

Great post Jesse.  One thing to note on the changing data.  Instead of List<T> use ObservableCollection<T> and then you can just change the data and the chart is already databound to the ObservableCollection, and will change dynamically.

# Silverlight Travel » Diagramme mit dem Silverlight Toolkit said on 25 November, 2008 01:31 AM

Pingback from  Silverlight Travel &raquo; Diagramme mit dem Silverlight Toolkit

# Graphen - Silverlight Toolkit at Programming with Silverlight, WPF & .NET said on 25 November, 2008 01:42 AM

Pingback from  Graphen - Silverlight Toolkit at Programming with Silverlight, WPF &amp; .NET

# 2008 November 25 - Links for today « My (almost) Daily Links said on 25 November, 2008 04:33 AM

Pingback from  2008 November 25 - Links for today &laquo; My (almost) Daily Links

# HOW TO: Graphing in Silverlight | Seavista Software Blog : Internet Developer Ramblings said on 25 November, 2008 10:47 AM

Pingback from  HOW TO: Graphing in Silverlight | Seavista Software Blog : Internet Developer Ramblings

# Dew Drop - November 25, 2008 | Alvin Ashcraft's Morning Dew said on 25 November, 2008 11:44 AM

Pingback from  Dew Drop - November 25, 2008 | Alvin Ashcraft's Morning Dew

# Dew Drop - November 25, 2008 | Alvin Ashcraft's Morning Dew said on 25 November, 2008 11:44 AM

Pingback from  Dew Drop - November 25, 2008 | Alvin Ashcraft's Morning Dew

# Community Blogs said on 26 November, 2008 11:02 PM

In this issue: Jonathan van de Veen, Bart Czernicki, Tim Greenfield, Ben Waggoner, Ning Zhang, Jesse

# 8 bit music | Intel.com said on 28 November, 2008 09:47 PM

Pingback from  8 bit music  | Intel.com

# Delay's Blog said on 06 February, 2009 02:29 AM

It's been a couple of months since I shared my semi-comprehensive page of Charting resources on the web

# Felix Wang | Evangelizing the Next Web said on 11 February, 2009 12:48 AM

Overviews ( 100 level ) Silverlight Toolkit Released – More controls! - Tim Heuer 's during the PDC keynote

# DotNetClub Complutense Madrid said on 19 February, 2009 04:09 AM

En el blog de Felix Wang , he encontrado este art&iacute;culo donde se agrupan una colecci&oacute;n de

# Top-silverlight » Blog Archive » My new home page, extended [Updated collection of great Silverlight and WPF Charting resources!] said on 03 June, 2009 03:11 AM

Pingback from  Top-silverlight  &raquo; Blog Archive   &raquo; My new home page, extended [Updated collection of great Silverlight and WPF Charting resources!]