How to set silverlight column chart style programatically

Let me wish a happy new year to all our blog readers.

This is first post of year 2010 and I decided to write my favorite topic of all times, Data Analysis and Visualization. These days I am working on a Silverlight application that involves very extensive use of charts for data visualization. And I use charting controls provided by Microsoft in Silverlight tool kit.

There are lot of examples available out there that shows you how to use these controls and how to style them. When it comes to styling and things like that, majority of the examples are focused around modifying control template or modifying styles in XAML file itself. Lot of time you make decisions about the type of chart and style of chart at run time based on data that needs to be visualized.

In this post I am going to focus on following tasks:

  • How to add a chart series programatically
  • How to set style of chart series programtically
  • How to set colors of columns in silveright charts programtically

Following image shows you a multi-series column chart. It shows three types of values at different intervals. One of the driving factor behind adding the column series was that I did not know how many different types of values are going to be returned in the data. So I could not simply add X number of ColumnSeries on XAML to say that I need to draw multi-series column chart with 3 points or things like that.

silverlight multiseries column chart

Following code snippet shows how I added column series in the main chart controls and how I specified different colors of the bars that are going to represent each type of data point.


foreach(LatencyColumnPlotData plotData in _latencyDataValues.ColumnPlotValues)
{
var series = new ColumnSeries();
var style = new Style(typeof (ColumnDataPoint));
SolidColorBrush bgBrush = (idx==1) ? 
    new SolidColorBrush(Colors.Blue) : 
    new SolidColorBrush(Colors.Orange);
var setterBg = new Setter(ColumnDataPoint.BackgroundProperty, bgBrush);
style.Setters.Add(setterBg);
series.DataPointStyle = style;
series.ItemsSource = plotData.DependentValues;
series.IndependentValueBinding = null;
series.Title = (idx == 1) ? "Average" : "Current";
idx++;
latencyChart.Series.Add(series);
}

var thresholdSeries = new ColumnSeries();
thresholdSeries.IndependentValueBinding = null;
thresholdSeries.ItemsSource = _latencyDataValues.ThresholdLatencyValues;
thresholdSeries.Title = "Threshold";
var bg = 
   new Setter(ColumnDataPoint.BackgroundProperty, new SolidColorBrush(Colors.Green));
var bgStyle = new Style(typeof(ColumnDataPoint));
bgStyle.Setters.Add(bg);
thresholdSeries.DataPointStyle = bgStyle;
latencyChart.Series.Add(thresholdSeries);

Search

Social

Weather

18.1 °C / 64.6 °F

weather conditions Clear

Monthly Posts

Blog Tags