Visual Studio does not provide a chart control by default for use in WinRT apps but we can get around this by using the ones provided in the WinRT XAML Toolkit.
Getting Started
Create a new blank Windows Store project in Visual Studio and then add the two NuGet packages listed below – searching in the NuGet package manager for “WinRT XAML Toolkit” should bring them both up.
Creating an empty chart
In MainPage.xaml add the following XAML namespace reference.
xmlns:Charting="using:WinRTXamlToolkit.Controls.DataVisualization.Charting"
Now lets add an empty chart that we’ll use to hold the chart type that we are interested in.
<Charting:Chart Name="MyChart" Width="500" Height="500" Title="My Chart" Margin="0">
</Charting:Chart>
Adding a Pie Chart
There are many different types of chart that can be created but for the sake of simplicity we will just create a pie chart in this tutorial.
<Charting:Chart Name="MyChart" Width="500" Height="500" Title="Chart" Margin="0">
<Charting:PieSeries Margin="0" IndependentValuePath="Item1" DependentValuePath="Item2" IsSelectionEnabled="True" />
</Charting:Chart>
Note that IndependentValuePath determines what we want to show on each pie segment like its name and DependentValuePath determines the size of each pie segment. I’ve set them to “Item1” and “Item2” as we are using a Tuple to pair the values together as you will see below.
Populating the pie chart
Open the code behind file for MainPage.xaml and add the following code which will create three segments in the pie chart.
public MainPage()
{
this.InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
List<Tuple<string, int>> myList = new List<Tuple<string,int>>()
{
new Tuple<string, int>("Item 1", 20),
new Tuple<string, int>("Item 2", 30),
new Tuple<string, int>("Item 3", 50)
};
(MyChart.Series[0] as PieSeries).ItemsSource = myList;
}
If you build you application you should see a pie chart with three segments shown onscreen. That’s all for this tutorial but stay tuned for more on the WinRT XAML Toolkit.