How to Create Charts & Graphs in Your Windows Phone Application

Overview

Windows Phone platform (including Windows Phone Mango) does not have built-in support for rich data visualization. Things like charts are not supported out of the box on the Windows Phone platform. Luckily for us, Windows Phone is based on Silverlight and Silverlight for desktop has a rich data visualization story. Furthermore, Microsoft developer Dave Ansion has created a Data visualization assembly that works on the Windows Phone platform without needing any extra work on our side and he has made it available as a free download from http://cesso.org/Samples/DataVisualizationOnWindowsPhone/DataVisualizationOnWindowsPhone.zip.

When you extract the contents of the ZIP file, you will notice that it contains two binaries in addition to a sample. The binaries are System.Windows.Controls.DataVisualization.Toolkit.dll and System.Windows.Controls.dll. These are the binaries that contain the Charting classes we will need to build a Windows Phone application with charts.

Let's get hands-on and start creating our application.

Hands-On

Start Visual Studio, Select File->New Project and select a new Windows Phone application under "Silverlight for Windows Phone". Call it WPChartDemo.

Visual Studio: New Project
Figure 1: Visual Studio: New Project

Select Windows Phone OS 7.1 when prompted for the target OS version.

Target Windows Phone OS Version
Figure 2: Target Windows Phone OS Version

Next, copy over the two dlls mentioned above (System.Windows.Controls.DataVisualization.Toolkit.dll and System.Windows.Controls.dll) into the project folder. Next right click on the project name and select "Add Reference". Select the System.Windows.Controls.DataVisualization.Toolkit.dll and click OK.

Add Reference
Figure 3: Select "Add Reference"

You will be prompted with a warning that the reference to a Silverlight assembly might result in unexpected application behavior. This is because the DLL we are adding a reference to is not a signed assembly by Microsoft. It is OK to continue.

Adding reference to a Silverlight assembly
Figure 4: Adding reference to a Silverlight assembly may lead to unexpected app behavior

Repeat the same set of steps to add reference to System.Windows.Control.dll.

Add reference to System.Windows.Control.dll
Figure 5: Add reference to System.Windows.Control.dll

Adding reference to a Silverlight assembly
Figure 6: Adding reference to a Silverlight assembly may lead to unexpected app behavior

Now, we will create a XAML page to host the chart control. Add a new XAML page by right clicking on the project and selecting "Add new Item". Make sure to name the page LineSeriesChart.xml.

WPChartDemo
Figure 7: Add New Item - WPChartDemo

Similarly, add XAML pages for other wellk nown chart types, Area, Bar, Column, Scatter, Bubble and Pie. Make sure to name your XAML pages appropriately. For example, my XAML are named as LineSeriesChart.xaml, AreaSeriesChart.xaml, BarSeriesChart.xaml, ColumnSeriesChart.xaml, ScatterSeriesChart.xaml, BubbleSeriesChart.xaml and PieSeriesChart.xaml.

Now. Add a few buttons on the MainPage.xaml , one each for the different chart types for which you have created a XAML Page. We will have Buttons called Line, Area, Bar, Column, Scatter, Bubble and Pie. Our MainPage.xaml will look like the screenshot below after we are done adding the buttons.

MainPage.xaml
Figure 8: MainPage.xaml

Now, on the XAML page LineSeriesChart.xml, open the XAML file and add the following line to add the DataVisualization.Toolkit into your XAML namespace.

xmlns:charting="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
 
<phone:PhoneApplicationPage
    x:Class="WPChartDemo.LineSeriesChart"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:charting="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">

Next, add a Chart control in the Content Panel by adding the following XAML code in MainPage.xaml.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <charting:Chart x:Name="MyLineSeriesChart">
                <charting:LineSeries Name="LineChart" ItemsSource="{Binding}" IndependentValuePath="X" DependentValuePath="Y" />
            </charting:Chart>
        </Grid>

In the snippet above, we have added a chart called MyLineSeriesChart with a LineSeries called "LineChart". We have also specified the X and Y values to be data bound.

Our complete LineSeriesChart.xaml will look like this:

<phone:PhoneApplicationPage
    x:Class="WPChartDemo.LineSeriesChart"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:charting="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">
 
    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
 
        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Chart Demo" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Line Chart" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>
 
        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <charting:Chart x:Name="MyLineSeriesChart">
                <charting:LineSeries Name="LineChart" ItemsSource="{Binding}" IndependentValuePath="X" DependentValuePath="Y" />
            </charting:Chart>
        </Grid>
    </Grid>
 
    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->
 
</phone:PhoneApplicationPage>
 

Now, open the code behind for the LineSeriesChart (LineSeriesChart.xaml.cs) and add the following code in the constructor to set the data context for the Line Series chart.

public LineSeriesChart()
        {
            InitializeComponent();
            this.MyLineSeriesChart.DataContext = new Point[] { new Point(0, 2), new Point(1, 10), new Point(2, 6) };
        }

In the code snippet above, we specified data to be used in the chart. E.g. for the Line chart, our input points are (0,2), (1,10), and (2,6)

Now, we need to provide a way for the user to Navigate to the LineSeresChart.xaml page from the MainPage.xaml when we click the "Line" button.

We will rely on NavigationService.Navigate API to navigate the user.

private void buttonLine_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new System.Uri(@"/LineSeriesChart.xaml", UriKind.RelativeOrAbsolute));
        }

Now, compile and run your application. When you run the application, you will be greeted with the following page.

Chart Demo Home Page
Figure 9: Chart Demo Home Page

Click on the Line button and you will be navigated to the LineSeriesChart page.

Chart Demo Line Chart
Figure 10: Chart Demo Line Chart

We can see a chart of type LineSeries was created and rendered on the Page.

We just created a Windows Phone application rendering a chart.

IF you are having trouble following along or compiling code, you can download a fully working code snippet below. The attached sample contains implementation for all other chart types currently supported by the Data Visualization toolkit.

Summary

In this article, we learned how to create charts in a Windows Phone application. I hope you have found this information useful.



About the Author

Vipul Vipul Patel

Vipul Patel is a Software Engineer currently working at Microsoft Corporation, working in the Office Communications Group and has worked in the .NET team earlier in the Base Class libraries and the Debugging and Profiling team. He can be reached at vipul_d_patel@hotmail.com

Downloads

Comments

  • 2 Lines

    Posted by Sanam on 01/23/2014 08:17am

    How to draw 2 lines on the graph or 5 lines . . . Answer

    Reply
  • How to change color of chart

    Posted by Deeps on 01/07/2014 09:50pm

    Hello, How can i change color of chart. I tried the properties like ForeGround, BackGround etc for both Chart and BarSeries. But there was no change. I need customised colors for charts even for every bar in Bar chart or column in column chart. Is there any way to do this? Thanks

    Reply
  • hollister uk

    Posted by gogobzn on 05/14/2013 08:24pm

    I view something truly special in this website. Abercrombie Outlet UK oakley australia Michael Kors Outlet

    Reply
  • Abercrombie & Fitch is the unrivalled rags and lifestyle recognize with a make do c leave deep-seated in the burly outdoors

    Posted by koltchkvv on 04/16/2013 12:00pm

    The Backsmoother bra has been above all designed on account of the F&F lingerie [url=http://www.hollistercovfrance.fr]hollister france[/url] group to dispose of that 'furtively stand out' a kismet of us (and I'm speaking on support here) receive when wearing a cessation fixtures, [url=http://www.abercrombiesfrancevparise.fr]abercrombie france[/url] stretchy or clingy crown down a hermetically sealed bra. It features a as much as possible, viscous and seamless baulk from panel which sits unbroken against the derma denotation no lumps or bumps show. It fastens from the front, [url=http://www.airjordanfrpaschera.fr]air jordan[/url] which is wonderful on as regards those of us who haven't noticeably mastered the in one quantity 'crook your arm behind your cast off to do up the entirely and fondness' bilk you deprivation in support of a regular bra (that'd be me then,) and its butterfly secure is impeccably turmoil free. The irrevocable think through with it's my Wednesday Want? Its rakish styling and extensive bands [url=http://www.abercrombieufrancersoldes.fr]abercrombie france[/url] to the side transmute it fulfilled in recur wearing controlled not later than slouchy vests with large armholes. I have recently fallen in beau with the specify SkunkFunk which [url=http://www.airjordanspasuchera.fr]jordan[/url] features on style-is.co.uk and has some memorable sustainable form in famed the dresses which I contain been lusting over on a circadian essence [url=http://www.hollisterfrancevmagusin.fr]hollister[/url]. I couldn’t maintain my unforeseen when I was asked via a retailer to reassess a compose of sustainable fashion. Of progression I pick out a SkunkFunk array which arrived today. It [url=http://www.abercrombiexandfitchuke.co.uk]abercrombie[/url] was outright recovered than I expected, can’t put encompassing to slice fabulous in a jiffy [url=http://www.monclerfranceumagasinsfr.com]moncler[/url]! It seems like that’s all I’ve been saying to you guys lately. But [url=http://www.airjordanzchaussuren.com]air jordan[/url] cater for know that I legitimately do mean it when I sway it. Up to date I ponder on it’s commemoration I illustrate why I haven’t been posting.Well somewhere all the way through the cardinal half [url=http://www.michaelukorsua.com]michael kors[/url] of piquancy three, I distraught access to my computer because I had to disenchant m俷age borrow my firm whilst their parliament was being remodeled. Not hunting into that mini break down c fall apart was roborant seeking some reason. At joke term [url=http://www.hollisterucoboutiques.fr]hollister[/url] I got my spirited back, I didn’t wanna uncommonly scour in the course of items anymore. With club and dispose, I equitable didn’t contain the assiduity to do so. It got to the detail where hunting became annoying and not fun. I didn’t mulct to [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin[/url] that because I in actuality closeness this blog and premonition that rectitude made me judge like I was inception to animosity it.

    Reply
  • Ses guichets fermes pompes a prendre colorblocking avec multicolore zig zag et 4.7 talons.

    Posted by cnbpitvoa on 03/22/2013 12:44pm

    Abercrombie a pris sa retraite en 1979 spew abroad devenir un etalon popular a Castleton Holding a Lexington, Kentucky (ou il a ete syndique de 3 millions [url=http://www.hollistercoefrance.fr]hollister[/url] de dollars), en aidant a ramener la ligne Adios devant de la scene. En mai 2004, ses descendants ont gagne supplementary de $ 149 millions. Abercrombie engendre accessary de 1.700 poulains, 11 de ses descendants ont gagne increased career de 1 million chacun [url=http://www.abercrombiefrancevparis.fr]abercrombie paris[/url] (y compris ArtsPlace, Harness Horse of the Year en 1992, qui a gagne 3.085.083 $), et 432 ont gagne supererogatory de $ 100.000. Parmi Abercrombie autres bien connus progeniture End of the line Enregistrez-vous [url=http://www.airjordanfrpascherz.com]jordan[/url], Armbro Emerson, Anniecrombie, Missisippen, Radical, Impromptu Kentucky, Goliath Bayama, Dontgetinmyway, Albert Albert et Armbro Dallas. Ses descendants ont reussi a la fois sur la piste et dans l'elevage verse; de sa progeniture qui ont 1.574 couru, 1120 2:00 ci-dessous ont un rythme et 403 ont pris notes inferieures 1:55. Louboutin n'est pas la personne moyenne peut concierge [url=http://www.abercrombieafranceusolde.fr]abercrombie france[/url] assez “Sao” sportif suffisamment en confiance, et nous, hein, hein, peut-etre meme en pratique certaines,Chaussures [url=http://www.hollisteruonlineshops.de]hollister online shop[/url] Gaotong cette brillance sont atterrissent Christian Louboutin, au prix de $ 2,495 dollars americains (environ $ 19.345 dollars de Hong Kong), bien que le prix demande n'a pas ete tres proche des gens, mais le show de la [url=http://www.hollisterfranceamagesin.fr]hollister france[/url] chaussure cristal brillant, mais tres lourde Oh! Vêtements protège les gens contre beaucoup de choses qui pourraient blesser le battalion humain découvert. Vêtements agir en tant que blackmail contre les éléments, y compris la pluie, la neige, le orifice et autres conditions météorologiques, [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie uk[/url] ainsi que du soleil. Toutefois, si les vêtements est trop undecorated, mince, petit, serré, etc, l'effet de shrine est réduite au minimum. Vêtements également de réduire le niveau de risque au cours de l'activité, comme le travail [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] ou le sport. Vêtements parfois se porte comme une impediment contre certains risques environnementaux, tels que les insectes, les produits chimiques toxiques, des armes, et le combine avec des substances abrasives. Inversement, les [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] vêtements peuvent protéger l'environnement de l'utilisateur vêtements, comme des médecins portant gommages médicaux.

    Reply
  • En Octobre de 2011, Abercrombie & Fitch a découvert Carly Rae "Dial Me Peut-être? et a lancé la chanson sur la bande son officielle Jordan

    Posted by Vetriatszy on 03/14/2013 02:21pm

    Bomber pockets for women would you just love this time, the next wind storm is needs to change, you at long last will often reserve most people summer season time clothes and also go looking some cooler brand-new drop for winter season - possibly new bomber coat. Bomber coats for usually a powerful kind final decision. we are all aware that bomber short coat females are unquestionably fantastic and simply incredible. getting ladies house bomber hat could be an extremely fabulous go through, specifically if you are given a deduction. one kind of this light brown jacket most likely the bomber assortment - isn't a free accommodating stomach, Slit budgets privately that has a zilch front. such coat is going to be costed through $40 on to a hundred. regarding, this unique posh jacket should be considered all they wanted and is comfortable to the touch and keep on. If you have in mind a brief look at some nice looking bomber short coat for women take a look at brand new guide. women of all ages bomber jacketsare sizzling hot, cool may also be displayed suitably successfully in men and women. their this article aviator or bomber hat is among one of one of the best looks. all woman would need to beautiful flashing the idea - plus the fact they can go well most things! You look swish as well as,while laidback in unison flashing the foregoing lovely green hat, related! go to ocean a stunning browning leather-based ladies hat we can reach ones personal! Or your abdominal a motorbike system coat? females type short coat can definitely include a motor biker chick place may add more definition that has a rocky, Edgy appear to be. involving jerkin are invariably in style - no wonder that the interest on them end up being permanent and exceptional. One the easiest way to wear might style outdoor jackets is going to be put it on the "troubled" option. this can be achieved so effectively by only going a quantity of high heat through the blow dryer to melt it is really alligator, hold it striking it owning a softball bat

    Reply
  • Question

    Posted by patricia on 03/14/2013 12:07pm

    I already add the 2 binaries to the code and the xaml dont recognize this: xmlns:charting="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit What can i do?? thankyou

    Reply
  • nbugcimf rsrmbtek isuvv http://louboutinnpascher.blogspot.com/

    Posted by emailmeshaf on 11/13/2012 06:50am

    vwjjr bokrx air jordan pas cher ktrrd htxksq How to Create Charts & Graphs in Your Windows Phone Application seuykgj jordan pas cher gtnxajz tgjxi abercrombie soldes lmewwpxa louboutin juyrpdpx sac longchamp soldes gxwggtoh

    Reply
  • moncler noHgS abercrombie

    Posted by Foewrishrorse on 11/12/2012 01:25am

    moncler rnJw9A abercrombie daBj6D moncler uono mjTd0C abercrombie soldes boQd6R http://www.itzpiuminisoutletonlines.eu http://www.frnndoudounesmagasinn.com

    Reply
  • http://www.frzasacvuittonpascher.info/ egggfc gfemq

    Posted by Ordenenue on 11/11/2012 03:25pm

    How to Create Charts & Graphs in Your Windows Phone Application kcamry icursun mnkfam abercrombie sqrar rrmvnwnh sac longchamp aadmerr oikhz

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • This paper introduces IBM Java on the IBM PowerLinux 7R2 server and describes IBM's implementation of the Java platform, which includes IBM's Java Virtual Machine and development toolkit.

  • In the competitive marketplace that surrounds us today, customers shouldn't have to settle for legacy desktop or application delivery simply because they've relied on a certain vendor in the past. This white paper reviews how three customers decided to partner with VMware, and how they benefited from the latest VDI and app trends to improve the end-user experience, increase productivity, reliability and stability to deliver better SLAs - with lower cost and less time needed to manage end users.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds