Bar and Line graph in Silverlight 4.0

Graphs contribute nice visual presentation to the data. There are several instances where you can use graphs like dashboard.

Today, we will look at Silverlight toolkit data visualization controls, bar charts and line charts. There are several others to choose from and they all follow same data binding as two we are going to look at.

Screenshot:

Before you start, if you don't already have, you need to download Silverlight toolkit 4.0 from codeplex website: http://silverlight.codeplex.com/

Once this is installed:

  1. Create a new project with Silverlight application template
  2. Add reference to System.Windows.Controls.DataVisualization.Toolkit
  3. Add namespace at the top of Main.xaml file as shown:

xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"

 

After adding above line your user control tag would look like this:

<UserControl x:Class="ChartSetts.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"

mc:Ignorable="d"

d:DesignHeight="300" d:DesignWidth="400">

 

After adding namespace lets add chart and series to chart

<chartingToolkit:Chart x:Name="barChart" Title="Bar Chart">

<chartingToolkit:ColumnSeries DependentValuePath="Value" Title="Bar"

IndependentValuePath="Key"

ItemsSource="{Binding}" />

<chartingToolkit:LineSeries DependentValuePath="Value" Title="Line"

IndependentValuePath="Key"

ItemsSource="{Binding}" />

</chartingToolkit:Chart>

 

Once this is done: let's add some code to add dummy data to our series:

public MainPage()

{

InitializeComponent();

List<KeyValuePair<string, int>> chartData = new List<KeyValuePair<string, int>>();

chartData.Add(new KeyValuePair<string, int>("March", 2002));

chartData.Add(new KeyValuePair<string, int>("April", 1950));

chartData.Add(new KeyValuePair<string, int>("May", 1980));

PieChart.DataContext = chartData;

barChart.DataContext = chartData;

}

 

This is it.

Last but not the least: Build your project and run

Tags: , ,

Silverlight 4.0