Peter McGrattan’s Weblog

Silverlight, WCF, ASP.NET, AJAX, Graphics, RIA

Silverlight 2.0 Pie Chart (Beta)

Posted by petermcg on May 18, 2008

Edited on 26/June/2008 : Code download and Demos updated to support Silverlight 2 Beta 2

Edited on 20/October/2008 : Code download and Demos updated to support Silverlight 2 RTW

Basic Pie Chart Live Demo

Video Pie Chart Live Demo

Code Download for Silverlight 2 RTW

In an attempt to demonstrate some of the powerful 2D graphics support in Silverlight 2.0, I recently developed a re-usable implementation of a pie chart.  Having lately read some forum postings asking for a pie chart that works with Silverlight 2.0, I thought I’d publish what I’ve come up with.

Full source code and demos are available, the following headings show some of the main features as well as examples of pie charts you can create :

1. Basic Silverlight 2.0 Pie Chart :

Basic Pie Chart

2. Supports Radial Gradient, Linear Gradient and Video segments :

Linear Radial Video

3. How to create basic Pie Chart in XAML only :

<charts:PieChart x:Name="pieChart1" Center="150.0,150.0" Radius="100.0"
                 Stroke="LightGray" StrokeThickness="2.0" FontSize="10">
    <charts:PieSegment Percentage="35" Foreground="Orange" />
    <charts:PieSegment Degrees="38" Foreground="Blue" />
    <charts:PieSegment Degrees="72" Foreground="Green" />
    <charts:PieSegment Degrees="101" Foreground="Red" />
    <charts:PieSegment Degrees="23" Foreground="Purple" />
</charts:PieChart>

4. How to create basic Pie Chart in C# only :

PieChart pieChart1 = new PieChart()
{
    Center = new Point(150.0, 150.0),
    Radius = 100.0,
    Stroke = new SolidColorBrush(Colors.LightGray),
    StrokeThickness = 2.0,
    FontSize = 10.0,
    Segments = new PieSegmentList()
    {
        new PieSegment() { Percentage = 35, Foreground = new SolidColorBrush(Colors.Orange) },
        new PieSegment() { Degrees = 38, Foreground = new SolidColorBrush(Colors.Blue) },
        new PieSegment() { Degrees = 72, Foreground = new SolidColorBrush(Colors.Green) },
        new PieSegment() { Degrees = 101, Foreground = new SolidColorBrush(Colors.Red) },
        new PieSegment() { Degrees = 23, Foreground = new SolidColorBrush(Colors.Purple) }
    }
};

// XAML contains <Canvas x:Name="Canvas1" />
Canvas1.Children.Add(pieChart1);

5. Specify segment size in Degrees or as a Percentage :

Percentage or Degrees - Highlighted

6. View changes as you type in Visual Studio 2008 Silverlight 2.0 Designer :

Silverlight 2.0 Designer

7. Implemented using Dependency Properties and ObservableCollection :

The chart will re-draw at runtime when you specify a new Segments Collection or modify the Center or Radius properties for example.

// Chart will redraw at new size and location
pieChart1.Radius = 150.0;

pieChart1.Center = new Point()
{
    X = 150.0,
    Y = 250.0
};

This provides support for databinding, animation of the chart.  View the demos and download the code for more information.

8. Efficient drawing and smooth mouse over animation :

Chart is drawn efficiently using framework classes in the System.Windows.Shapes and System.Windows.Media namespaces such as Path, LineSegment, ArcSegment and TranslateTransform.  MouseEnter animation is smooth, using a Storyboard in the System.Windows.Media.Animation namespace to animate the rendering of a TranslateTransform.

9. View running demos and download source :

Basic Pie Chart Live Demo

Video Pie Chart Live Demo

Code Download for Silverlight 2 RTW

Let me know any thoughts, requests, questions etc by posting a comment, it will help prioritise my todo list and I’m only too happy to hear if this is useful to you or not.

About these ads

39 Responses to “Silverlight 2.0 Pie Chart (Beta)”

  1. ganttchartseeker said

    You know how to develop an gantt chart in silvrlight beta?

  2. Peter McGrattan said

    Hi Ganttchartseeker, There are several ways to create something simple like this in Silverlight 2.0. A Gantt chart is not dissimilar to a horizontal bar chart. One approach could use a StackPanel, Grid or ListBox control as a list where each item contains a simple rectangle or Usercontrol and possibly customize the Calendar control for the project schedule. This post from the silverlight.net forums may be of interest to you.

  3. […] Silverlight 2 Pie Chart: Peter McGrattan has posted a nice control and article that demonstrates how to use a new Silverlight charting control he has written. […]

  4. […] Silverlight 2 Pie Chart: Peter McGrattan has posted a nice control and article that demonstrates how to use a new Silverlight charting control he has written. […]

  5. […] Silverlight 2 Pie Chart: Peter McGrattan has posted a nice control and article that demonstrates how to use a new Silverlight charting control he has written. […]

  6. […] Peter McGrattan’s Blog […]

  7. […] Источник: блог Питера МакГрэтена. […]

  8. […] Silverlight 2 Pie Chart: Peter McGrattan贴出了一个很好的控件和相应文章,示范如何使用他编写的一个新Silverlight图表控件。 […]

  9. Eric said

    When I try to run the sample in Win2003/IE6, I get an silverlight error:
    ErrorCode:5014, ParseError, illegal xml character, demo.xap, line 1, position 3

  10. Peter McGrattan said

    Hi Eric, I’ve tested both demos (basic and video) and building/running the Visual Studio 2008 solution on Win2003 with IE 6 and can confirm everything is working fine for me.

    If other Silverlight 2.0 Beta 1 applications do not work on that machine then check you have the ‘Silverlight 2.0 Beta 1 Runtime’ installed properly, if not follow the steps here.

    If the runtime is installed correctly, the problem could possibly be related to the locale you are using to view the demos.  In Windows this setting is controlled by the Regional Options Control Panel applet and the Language Bar.  In Silverlight Beta 1, the installation and control runtime are available in English.  Silverlight Beta 1 does not support end to end application localization. This support will be introduced for Beta 2.

    If the runtime is installed correctly and your English locale is supported by Silverlight 2.0 Beta 1, then have a look in the comments here and here for evidence that at least one Microsoft team is aware of ‘a known issue that generates this error code’ and that closing and restarting your browser appears to be a workaround.

    Bear in mind that Silverlight 2.0 is in it’s first Beta and there will be problems; equally there will be time for problems like this to be resolved.  Thanks for your feedback and for trying out the Pie Chart Beta!

  11. […] Diagramas en Silverlight 2: Peter McGrattan ha posteado un control y un artículo en el que nos enseña a usar el control de diagramas para Silverlight que ha hecho. […]

  12. […] Silverlight 2 Pie Chart: Peter McGrattan has posted a nice control and article that demonstrates how to use a new Silverlight charting control he has written. […]

  13. […] Silverlight 2 Pie Chart: Peter McGrattan has posted a nice control and article that demonstrates how to use a new Silverlight charting control he has written. […]

  14. Hi Peter,
    Your control is Nice control, Thanks for posting this article.

    I have some quries regarding to feteching data from SQL Server 2005 and give input to your Graph. Without using WCF, Can we not use LINQ.
    Please help me to provide data from SQL server to SL control or your graph control.

    I am waiting your reply

  15. […] Silverlight 2 Pie Chart: Peter McGrattan has posted a nice control and article that demonstrates how to use a new Silverlight charting control he has written. […]

  16. Peter McGrattan said

    Hi Dattatray Patil, There are several tutorials available that show how to access data from SQL server 2005 in a Silverlight application as well as how to use LINQ, have a look here for a start.

    Once you’ve retrieved your results, create the relevant PieSegment objects and add them to the Segments collection as shown in this post and the examples in the code download.

  17. […] Silverlight 2 Pie Chart: Peter McGrattan has posted a nice control and article that demonstrates how to use a new Silverlight charting control he has written. […]

  18. Volkan said

    Hi Peter,

    Thank you for posting this article and making the source code available. I’ve been looking for something like this.

    Keep up the good work.
    Thanks

  19. Todd Herman said

    I am most interested specifically in how you draw the pie segments. I understand the paths you used but I was wondering if you could help me in altering it slightly. I need to create a “doughnut” chart ( a pie chart with a hole in the middle). So, instead of wedge slices, I need to add a second arcSegment in the path.

  20. […] Graphique en pointe de tarte Silverlight 2: Peter McGrattan à publier un beau contrôle ainsi qu’un article qui démontre comment utiliser un nouveau contrôle de graphique Silverlight qu’il à lui-même écrit. […]

  21. Peter McGrattan said

    Hi Todd,

    Thanks for the comment, please see this post for an outline of how the functionality you requested has been added to the latest beta.

    Regards,

    Peter

  22. Lebza said

    Can I use for my commercial website or not. I’m dont understand the english they used on the licence terms

  23. Peter McGrattan said

    Hi Lebza,

    If you follow the Url at the top of License.txt you can get a translation of the main points of the current license in several different languages.

    Regards,

    Peter

  24. avarsh said

    hi,
    i want to know if we can have olap cubes shown in silverlight ? and also can charts can fetch data from cubes ?

    thanks !

  25. arseik said

    Hi Mc Grattan,
    great post!!

    I tried this in my project, working great!
    but, when i want to integrate with database it was getting problem[nothing changes]

    Step1:I created Silverlight project and created a webservice for accessing data from SQL Server.

    Step2: I Made the service reference to my webserver
    Step3:

    public partial class Page : UserControl
    {

    private PieChart basicPieChart = null;
    public Page()
    {

    InitializeComponent();

    Loaded += delegate
    {
    basicPieChart = new PieChart()
    {
    Center = new Point(150.0, 150.0),
    Radius = 100.0,
    Stroke = new SolidColorBrush(Colors.LightGray),
    StrokeThickness = 2.0,
    FontSize = 10.0,
    };
    };

    ServiceReference3.WebServiceSoapClient webserviceSoapClient = new Tellarindo.ServiceReference3.WebServiceSoapClient();
    webserviceSoapClient.GetPercentageAsync();
    webserviceSoapClient.GetPercentageCompleted += new EventHandler(webserviceSoapClient_GetPercentageCompleted);

    }

    void webserviceSoapClient_GetPercentageCompleted(object sender, Tellarindo.ServiceReference3.GetPercentageCompletedEventArgs e)
    {
    if(e.Error == null)
    {
    //Some Statements Statement1, Statement2.....
    //CPercentage, ChPercentage, YPercentage are the double datatype values, whose values are retrived from e.Result

    basicPieChart.Segments.Add(new PieSegment() { Percentage = CPercentage, Foreground = new SolidColorBrush(Colors.Green)});
    basicPieChart.Segments.Add(new PieSegment() { Percentage = ChPercentage, Foreground = new SolidColorBrush(Colors.Blue)});
    basicPieChart.Segments.Add(new PieSegment() { Percentage = YPercentage, Foreground = new SolidColorBrush(Colors.Brown)});

    }
    }

    }

    Step4: I Executed my Project [Nothing displays]

    So, Could you please help for solving this problem

    waiting for your reply…..
    ThanQ

  26. Peter McGrattan said

    Hi,

    In the current implementation the pattern to use when dynamically adding/removing pie segments programatically is to create a new PieSegmentList and when you are happy with it assign it to the Segments dependency property on the PieChart instance once, as this is a dependency property it will cause the chart to be redrawn. In this case the body of the webserviceSoapClient_GetPercentageCompleted method should look roughly like this :

    // Create new list
    PieSegmentList segments = new PieSegmentList();

    segments.Add(new PieSegment() { Percentage = CPercentage, Foreground = new SolidColorBrush(Colors.Green)});

    segments.Add(new PieSegment() { Percentage = ChPercentage, Foreground = new SolidColorBrush(Colors.Blue)});

    segments.Add(new PieSegment() { Percentage = YPercentage, Foreground = new SolidColorBrush(Colors.Brown)});

    // Now assign to Segments property
    basicPieChart.Segments = segments;

    Instead of making multiple calls to basicPieChart.Segments.Add first create a separate PieSegmentList and assign that to basicPieChart.Segments when you are happy with it.

    Hope this helps…

    Peter

  27. arseik said

    ThanQ for your Quick reply!!

    but it gives me same result[displaying nothing],
    for your information
    I’m sure that values of CPercentage, ChPercentage, YPercentage are Correct values[double datatyped].

    Could you please give me some more help!!

    ThanQ
    arseik

  28. Peter McGrattan said

    Hi Arseik,

    Check you have the correct version of Silverlight 2 installed, the pie chart sample has recently been updated to RTW along with all other samples on the blog.

    If you download the demo solution above you can see several examples of how to use the control in Xaml at design time and in code.

    Hope this helps,

    Peter

  29. Laurent said

    Hello Peter,

    I am very interested by using your work about SilverLight charts.

    Unfortunately, my company doesn’t let me download your source code from your site. It blocks it automatically for security reasons.

    Could you send me your zip file by email please ?

    Thank you very much and congratulation for your work !

    Laurent.

  30. Hello there.

    Firstly, thanks for your control and for making it publicly available.

    I’m trying to use it within an ItemTemplate for a ListBox but am having some difficulty getting it to work properly. Here’s the XAML I have:


    <ListBox x:Name="_listBox">
    <ListBox.ItemTemplate>
    <StackPanel>
    <TextBlock Text="{Binding Path=ExecutedPercentage}"/>
    <charts:PieChart ... >
    <charts:PieSegment Percentage="{Binding Path=ExecutedPercentage}" Foreground="Green" />
    <charts:PieSegment Percentage="{Binding Path=UnexecutedPercentage}" Foreground="Red" />
    </charts:PieChart>
    </StackPanel>
    </ListBox.ItemTemplate>
    </ListBox>

    …not sure if that’s going to look any good, so here it is in unescaped form…

    Anyway, the first problem was that Percentage was not a dependency property. I fixed that. However it still doesn’t quite work. I know that the DataContext for the ItemTemplate works because the text for the TextBlock binds correctly. It seems that the DataContext isn’t available within the PieSegment.

    There was an error message stating that PieSegment wasn’t providing the data item (it was null) because PieSegment wasn’t a FrameworkElement, so I changed the base class to that, and the warning went away. But still no banana.

    Oh, and a breakpoint in the getter of my property is not hit (apart from the first TextBlock binding), so I know it’s not reading the value.

    This is a real shame because I was super excited about having a pie chart as part of my item template. I think it would be very visually striking in my application.

    I’m no data binding guru, but I’m not sure that it’s right to define a binding within an instance of the observable collection here. Should PieSegmentCollection implement some other kind of interface or have a different base class?

    Hope you can help me out with this, though I know it’s a tricky one.

    Once again, thanks for sharing your code.

    Regards,

    Drew.

  31. Hi Drew,

    Thanks very much for your feedback. With the release of charting support provided in the Silverlight Toolkit I’ve not updated the pie-chart any further. I may get time to review this decision early next year and if so the points you raise around databinding will be a priority.

    Thanks again,

    Peter

  32. chaitanya pednekar said

    Hi peter,
    I am very interested by your work about SilverLight charts. i am extremly fresher to this silverlight technology. i want to draw a simple pie chart , so please help me.

    Looking for your reply.

    Warm regards,
    Chaitanya pednekar

  33. Indrajit said

    Excellent I have used your piechart to showcase sales dashboard but in semicircular speedometer or gauge way and also made business object to read KPI from xml or list…it works excellent

  34. gvdamn said

    Hi Peter,

    Under: “3. How to create basic Pie Chart in XAML only :” there is some code to implement the pie chart in XAML only. Adding this code doesn’t deliver the pie chart though. Do I have to add a reference of some sort? Thx.

  35. gvdamn said

    I added ‘xmlns:charts=”clr-namespace:Charts;assembly=Charts”‘ to my .xaml file and charts.dll to my directory, but no luck.

    Any help is much appreciated.

  36. Jack D said

    Excellent article. Just I integrated it in to WPF but mouse over animate and video chart not working. In video chart it show some error in VideoBrush. Simple pie chart working but mouse over animate not working. Any suggestion.

  37. я считаю: неподражаемо..

  38. XAЛAШKA said

    Данный пост на самом деле помог мне принять очень нужное для меня решение. За что автору отдельное спасибо! Жду от Вас новых сообщений!

  39. […] Silverlight 2 Pie Chart: Peter McGrattan has posted a nice control and article that demonstrates how to use a new Silverlight charting control he has written. […]

Sorry, the comment form is closed at this time.

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: