How to Create Charts & Graphs in Your Windows Phone Application

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

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

  • Feedback

    Posted by Deepak SHAW on 04/28/2016 11:30pm

    Thanks it was useful and also worked with window 8.1 (VS2013 after auto project conversion)

    Reply
  • Feedback

    Posted by srikanth on 06/21/2015 11:12pm

    article is so good

    Reply
  • developer

    Posted by jovirus on 10/17/2014 05:26am

    Hey Thanks for the post. I am doing a win8.1 app. Does the line chart support a customized object instead of point, btw, when I using KeyValuePair, it crashes. Message = "System.InvalidOperationException: Assigned independent axis cannot be used. This may be due to an unset Orientation property for the axis.\r\n at WinRTXamlToolkit.Controls.DataVisualization.Charting.DataPointSeriesWithAxes.GetAxes(DataPoint firstDataPoin...

    Reply
  • 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
  • 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
  • problem in code

    Posted by nikunj on 11/05/2012 04:20am

    following are the errors i am getting while trying to implement above code:- Error 1 The type 'charting:Chart' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built. Error 2 The type 'charting:LineSeries' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.

    Reply
  • Changing background

    Posted by yo on 08/09/2012 12:16am

    Is it possible to change the background of the chart and the x,y values.

    Reply
  • Graphs

    Posted by Graphs on 04/30/2012 05:26am

    Thank you for sharing your knowledge about How to Create Charts & Graphs in Your Windows Phone Application, i have fallowed your tips and created a graphs

    Reply
  • Awesome

    Posted by Robin on 04/18/2012 01:32am

    Thanks for this - been looking for a tutorial on this for a couple of days, all the other existing ones are out of date

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date