My Master's Thesis Problems and solutions encountered…

21Aug/103

Create a Pie Chart with Silverlight toolbox – MVVM

This post quickly shows how to create a pie chart in your MVVM Silverlight application, like the one shown below:

Pie chart MVVM Silverlight

Step 1: Add the System.Windows.Controls.DataVisualization.Toolkit into your project, and insert this at the top of your MyPage.xaml in the View:

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

Step 2: Insert the pie chart in MyPage.xaml. Notice the ItemSource, which we will bind to in the ViewModel.

 <charting:Chart HorizontalAlignment="Stretch"
                BorderBrush="Transparent"
                VerticalAlignment="Top" Height="170"
                Name="pieChart" Margin="0 -10 0 -10">

                <charting:Chart.Series >
                    <charting:PieSeries ItemsSource="{Binding ChartItems}"
                          IndependentValueBinding="{Binding Key}"
                          DependentValueBinding="{Binding Value}" >
                     </charting:PieSeries>
                </charting:Chart.Series>
</charting:Chart>

Step 3: In the ViewModel, create the following property, that will contain the array of the chart:


  private KeyValuePair<string, int>[] _chartItems;
         public KeyValuePair<string, int>[] ChartItems
         {
             get
             {
                 return _chartItems;
             }

             set
             {
                 _chartItems = value;
             }
         }

Step 4: In your ViewModels constructor, create the ChartItems and populate them.


    ChartItems = new KeyValuePair<string, int>[4];

             ChartItems[0] = new KeyValuePair<string, int>("Lorem ipsum dolor sit amet", 20);
             ChartItems[1] = new KeyValuePair<string, int>("Maecenas iaculis dapibus", 90);
             ChartItems[2] = new KeyValuePair<string, int>("Nulla facilisi. Curabitur laoreet", 112);
             ChartItems[3] = new KeyValuePair<string, int>("Pellentesque non turpis elit", 160); 

             //RaisePropertyChanged("ChartItems"); //Only necessary of you create the ChartItems outside the constructor

And that's it!

Of course, you will want to populate the chart with integers retrieved from a database, and in that case, just create properties for each of the items.

Comments (3) Trackbacks (0)
  1. nice post. thanks.

  2. Thanks for the post

  3. hi anyone post how to create charts in silverlight from database


Leave a comment



6 + seven =

No trackbacks yet.