How to Create Charts & Graphs in Your Windows Phone Application

Wednesday Mar 14th 2012 by Vipul Vipul Patel
Share:

Windows Phone (including Mango) doesn't come with built-in support for rich data visualization. Using a free download, Vipul Patel shows you how to get charts working on 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.

Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved