Introduction to Telerik RadControls for Metro (Pie Chart)

Following the previous Telerik RadControls Bar Chart post, in this post, I will reuse the StateData and Person data model to create a Pie Chart.

Pie Chart needs pie series with the ValueBinding (similart to Bar Chart). However, PieSeries does not have CategoryBinding which creates labels in Bar Chart. For the PieSeries we will need PieLabelStategy instead.

The code below shows how we put PieChart control in xaml page. Don’t forget to specify telerik namespace like we did in the Bar Chart post.

        <telerik:RadPieChart Grid.Row="1" PaletteName="DefaultDark"
                             x:Name="radPieChart">
        </telerik:RadPieChart>

In the code behind, I create PieSeries and binding. Like the Bar Chart sample, the ValueBinding is binded to StateData.Count (i.e., how many customers in the state). RadiusFactor property controls how big is our pie chart.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var peopleByStates = from p in SamplePeople.People
                                 group p by p.ResidenceState into g
                                 orderby g.Key
                                 select new { State = g.Key, People = g };

            var series = new PieSeries();
            series.RadiusFactor = 0.7;

            series.ValueBinding = new PropertyNameDataPointBinding("Count");
            // Set up label strategy
            var pieLabelStrategy = new PieLabelStrategy();
            pieLabelStrategy.Binding = new PropertyNameDataPointBinding("Name");
            var chartSeriesLabelDefinition = new ChartSeriesLabelDefinition();
            chartSeriesLabelDefinition.Strategy = pieLabelStrategy;

            series.LabelDefinitions.Add(chartSeriesLabelDefinition);

            var itemSources = new List<object>();
            foreach (var state in peopleByStates)
            {
                var item = new StateData { Name = state.State, Count = state.People.Count() };
                itemSources.Add(item);
            }
            series.ItemsSource = itemSources;
            radPieChart.Series.Add(series);
        }

To create a label strategy, we extend an abstact class Telerik.UI.Xaml.Controls.ChartSeriesLabelStrategy and override Options property, CreateDefaultVisual method, and GetLabelContent method. The CreateDefaultVisual method returns FrameworkElement instance that will represent the label while the GetLableContent method returns the label at the specified index.

public class PieLabelStrategy : ChartSeriesLabelStrategy
    {
        private string format = "{0}\n{1} ({2:P2})";

        public PropertyNameDataPointBinding Binding { get; set; }

        public override LabelStrategyOptions Options
        {
            get { return LabelStrategyOptions.Content | LabelStrategyOptions.DefaultVisual; }
        }

        public PieLabelStrategy()
        {
        }

        public override FrameworkElement CreateDefaultVisual(DataPoint point, int labelIndex)
        {
            var textBlock = new TextBlock()
            {
                Foreground = new SolidColorBrush(Colors.White),
                FontSize = 14.667 };
            return textBlock;
        }

        public override object GetLabelContent(DataPoint point, int labelIndex)
        {
            if (point == null || labelIndex < 0)
            {
                return base.GetLabelContent(point, labelIndex);
            }

            return string.Format(this.format, Binding.GetValue(point.DataItem), ((PieDataPoint)point).Value, ((PieDataPoint)point).Percent / 100);
        }
    }

Telerik does provide PieLabelStrategy sample, and I just modified it a little bit to provide my own label and FrameworkElement.

                /// <summary>
		/// Creates a <see cref="T:Windows.UI.Xaml.FrameworkElement"/> instance that will
		/// represent the label for the provided data point.
		/// </summary>
		/// <param name="point">The data point a label is needed for.</param>
		/// <param name="labelIndex">The index of the label. More than one label is supported
		/// per data point.</param>
		public virtual Windows.UI.Xaml.FrameworkElement CreateDefaultVisual(Telerik.Charting.DataPoint point, int labelIndex) {
return null;
}

		/// <summary>
		/// Gets the content for the label at the specified index, associated with the provided
		/// data point.
		/// </summary>
		/// <param name="point">The data point the label is associated with.</param>
		/// <param name="labelIndex"></param>
		public virtual object GetLabelContent(Telerik.Charting.DataPoint point, int labelIndex) {
if (point != null)
{
return point.Label;
}
else
{
return null;
}
}

You can download the full source code here. I include both Pie Chart and Bar Chart samples into one project with the top app bar buttons (which I used Syncfusion Metro Studio to create buttons) to navigate between two sample. Enjoy coding!

image

image

image

Advertisements

2 thoughts on “Introduction to Telerik RadControls for Metro (Pie Chart)

  1. Pingback: Playing with CalendarControl from Mindscape: Part 1 | Cyan By Fuchsia

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s