Sunday, August 8, 2010

Silverlight On Mobile : Charting on Windows Phone 7

Working in office on weekends and that too doing bug fixes in code which is written by others is pathetic job ! Well, After doing that finally got some time to explore new things on Windows Phone 7. I hope you enjoyed my last article on Splash Screen on Windows Phone 7. Today I am going to talk on Charting on Windows Phone 7.

Charting in Silverlight is nothing new to us since I have already wrote one article on that in past.Today I am going to push this charting feature to our Windows Phone 7 to have the same Data Visualization experience which we had inside browser in Desktop/Web version of Silverlight. Visifire is another player to introduce Charting Controls for Windows Phone 7 when I search across. If you know any more vendors who exposed their charting controls for Windows Phone 7 then do buzz back. Visifire unfortunately didn’t worked for me. So I finally decided to use our traditional Charting Controls provided by Silverlight 3 Toolkit.

Remember one thing that you will not have those controls sitting ready to go on your designer, First you need to install toolkit then you can set reference to the Charting Controls DLL like this :

ChartingDLLSystem.Windows.Controls.DataVisualization.Toolkit for our development.So you should expect output like this :

PieChartBarChartColumnChart
So,Lets do a simple Pie Chart. The methodology I am going to demonstrate for Pie Chart is exactly similar for Line,Bar,Column and other types of graph. For sake of Data to display on chart, I am going to Class and not actual data from Database since we are yet to explore service consumption in Windows Phone 7, However you feel you can do that then please go ahead and let me know if you have some issues.

XAML Code :

<mychrt:Chart x:Name="MyPieChart"                           
                             Title="Sample Chart" BorderBrush="{x:Null}" Background="{StaticResource TransparentBrush}" Margin="8,181,8,8" Style="{StaticResource ChartStyle1}" d:IsHidden="True">           
                <mychrt:PieSeries
                        Foreground="AliceBlue"
                        IndependentValueBinding="{Binding Name}"                  
                        DependentValueBinding="{Binding Sales}" Height="397" Margin="8,-22,-21,0" VerticalAlignment="Top" Style="{StaticResource PieSeriesStyle1}">
                    <mychrt:PieSeries.Background>
                        <ImageBrush Stretch="UniformToFill"/>
                    </mychrt:PieSeries.Background>
                </mychrt:PieSeries>
            </mychrt:Chart>

C# Code :

Namespaces :

using System.Collections.Generic;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Windows.Controls.DataVisualization.Charting;

Class Declaration :

#region ProductSales Class Declaration
       public class ProductSales
       {
           public string Name { get; set; }
           public double Sales { get; set; }
       }
#endregion

Class Implementation :

#region Public Method GetProductSales()
       public void GetProductSales()
       {
           List<ProductSales> PieData = new List<ProductSales>();
           PieData.Add(new ProductSales() { Name = "Vikram", Sales = 10.5 });
           PieData.Add(new ProductSales() { Name = "Chaitanya", Sales = 20.2 });
           PieData.Add(new ProductSales() { Name = "Manjiri", Sales = 30.2 });
           PieData.Add(new ProductSales() { Name = "Swati", Sales = 40.1 });

           PieSeries pieSlice = MyPieChart.Series[0] as PieSeries;
           pieSlice.ItemsSource = PieData;

           MyPieChart.LegendTitle = "Activity in this Month in %";
       }
#endregion

GetProductSales() Consumption :

// Constructor
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        #region Calling GetProductSales() to Bind Pie Chart
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
                GetProductSales();          
        }
        #endregion

and here is the output…

PieChart
Make a note that, you can apply Styles to this chart like I did, I made use of some brushes and styles to make it look good.I know this looks very old style, How if your same graph looks like this :

OputputGraphGraph

Lets make this look Jazzy … So I am taking example of a picture which I got while surfing. So lets add some nice background to graph by adding Image to Grid. Remember one thing, Though I am going to show the way how it will look jazzy,I warn you guys that should not go beyond limits and make it over jazzy else it will put performance down and then you might suffer. But yes, using right design is also need of application, So lets do it. Lets take one Image like this :

crop

If you want to adjust some properties or style you can do it via blend like this :

editor

Style
Same piece of code,only looks will be different. So here it will look like this :

perfumes

I hope you will find this information useful especially to represent your business data in form of Charts on your Windows Phone 7. I know we are not playing with real data but with real data methodology will remain same. So go ahead and try this out, If you find something unique or worth to discuss over here then do buzz back. Let’s meet again on this weekend with some new exciting feature of Silverlight On Mobile – Silverlight on Windows Phone 7.

Vikram.

10 comments:

Flex said...

Nice Post.........containing many usable information. I think it’s important to be ahead of the curve in terms of knowledge and capabilities.
---------------------

performance testing

arshad said...

Hi its really very nice blog,very useful information..Mobiles

Steven said...

Hi I have tried to implement your code but I does not work for me...
I get this error: Invalid attribute value charting:DisplayAxis for property TargetType. [Line: 762 Position: 12]

could you please post your app with the code.
Thanks for your help and great work

Steven said...

Hi thank you for your great code.
When I tried to implement it I get this error:
Invalid attribute value charting:DisplayAxis for property TargetType. [Line: 762 Position: 12]

could you please post your app with the source code.

Thanks

Vikram Pendse said...

Hi Steven,

After your comment, I re-run the app at my end and its working well without any compile/runtime errors.Could you please check your XAML code again or If you could send me a test mail at vikram[dot]pendse[at]puneusergroup[dot]org I can send you sample project which I used to blog here.

Thanks,
Vikram.

Karan Vohra said...

Hi Vikram,

I am getting the error - I
Invalid attribute value charting:DisplayAxis for property TargetType. [Line: 762 Position: 12]

The source code is as follows -

Vikram Pendse said...

Hi Karan,

After your comment, I re-run the app at my end and its working well without any compile/runtime errors.Could you please check your XAML code again or If you could send me a test mail at vikram[dot]pendse[at]puneusergroup[dot]org I can send you sample project which I used to blog here.

Thanks,
Vikram.

mJ said...

Hi,
Even I am getting the same error

Invalid attribute value charting:DisplayAxis for property TargetType. [Line: 762 Position: 12]

This error can be reproduced by simply dragging a chart control into the main page and running the project.

The program crashes at the very first line in the InitializeComponent :

System.Windows.Application.LoadComponent(this, new System.Uri("/XXXApplication;component/ABC.xaml", System.UriKind.Relative));

Vikram Pendse said...

Ohh :(

So sad to hear that guys,however its working fine at my end.I have also pass the same code to "Steven" who commented before you and also I got his reply as code is working,drop me a test mail either at vikram[dot]pendse[at]puneusergroup[dot]org and I will send code snippet to you. Please send test mail directly since I am not getting your email ids via comments.

Sorry for inconvenience if any

Vikram.

frankie said...

Hi,
I'm new to Silverlight charts for WP7. I'm trying to test your example on VS2010 but I have some errors on the 2 Style values (ChartStyle1,PieSeriesStyle1). Where can I find existant working templates?
Also... in first picture of your post a lot of references are added to the project. Are they necessary? I cannot find them, apart System.Windows.Controls.DataVisualization.Toolkit.dll

Can you, please, help me?

thanks,