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

Share

About Jesse Liberty

Jesse Liberty is an independent consultant and programmer with three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP, Microsoft MVP and Telerik MVP.
This entry was posted in z Silverlight Archives and tagged . Bookmark the permalink.

One Response to Graphing – Silverlight Toolkit

  1. pardxa says:

    Jesse , I am one of your readers of “Teach your self C++ in 24 hours” .It is my first book on programming almost 10 years ago. Now glad to read your article on Silverlight which I am learning. Thank you very much!

Leave a Reply

Your email address will not be published.