Click here to Skip to main content
15,867,308 members
Articles / Desktop Programming / WPF

Styling a Silverlight Chart

Rate me:
Please Sign up or sign in to vote.
4.85/5 (58 votes)
27 Jan 2009CPOL2 min read 262.9K   5.4K   87   47
A article on how to style a standard Silverlight chart to look like the Google Analytics chart.

GoogleAnalyticsGraph

Introduction

I love Google Analytics! I use it to monitor every site I own… Google’s chart looks very slick! Here is a walkthrough on how to style your Silverlight chart to look like the Google Analytics chart!

Before we start

We need some data. I created very basic TrafficInfo and TrafficInfoCollection objects with some dummy data that I can bind to.

C#
public class TrafficInfo
{
    public DateTime Date { get; set; }
    public int Visits { get; set; }
}

We also need the Silverlight Toolkit (I used the port to WPF created by Jaime Rodriquez).

Let's start with the basics

Add the following two namespaces:

XML
xmlns:charting="clr-namespace:Microsoft.Windows.Controls.DataVisualization.
                Charting;assembly=Microsoft.Windows.Controls.DataVisualization"
xmlns:datavis="clr-namespace:Microsoft.Windows.Controls.DataVisualization;
               assembly=Microsoft.Windows.Controls.DataVisualization"

Now, let's create a simple line chart:

XML
<charting:Chart Width="800" Height="175">
    <charting:Chart.Series>
        <charting:LineSeries IsSelectionEnabled="True"
                    Title="Visits"
                    ItemsSource="{StaticResource TrafficInfo}"
                    IndependentValueBinding="{Binding Date}"
                    DependentValueBinding="{Binding Visits}" />
    </charting:Chart.Series>
</charting:Chart>

And here is our master piece:

SilverlightChartTry1.jpg

Not bad, but…

Style, style, style

Let's start styling our chart… I will split the styling into two parts; the first part will be specific to line charts, and the second part might be relevant to other types of charts too…

Styling the LineSeries

Each LineSeries has a PolylineStyle property. The PolylineStyle controls how the line looks. Here is our GooglePolylineStyle:

XML
<Style x:Key="GooglePolylineStyle" TargetType="Polyline">
    <Setter Property="StrokeThickness" Value="5"/>
</Style>

And, here is the style for the LineDataPoint:

XML
<Style x:Key="GoogleLineDataPointStyle" TargetType="charting:LineDataPoint">
    <Setter Property="Background" Value="#0077CC" />
    <Setter Property="BorderBrush" Value="White"/>
    <Setter Property="BorderThickness" Value="2"/>
    <Setter Property="IsTabStop" Value="False"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="charting:LineDataPoint">
                <Grid x:Name="Root" Opacity="1">
                    <ToolTipService.ToolTip>
                        <StackPanel Margin="2,2,2,2">
                            <ContentControl Content="{TemplateBinding IndependentValue}" 
                                            ContentStringFormat="{}{0:MMMM d, yyyy}"/>
                            <ContentControl Content="{TemplateBinding DependentValue}" 
                                            ContentStringFormat="Visits {0:###,###,###}"/>
                        </StackPanel>
                    </ToolTipService.ToolTip>
                    <Ellipse StrokeThickness="{TemplateBinding BorderThickness}" 
                     Stroke="{TemplateBinding BorderBrush}" 
                     Fill="{TemplateBinding Background}"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Also update the chart’s LineSeries to use our newly created styles:

XML
<charting:LineSeries IsSelectionEnabled="True"
            PolylineStyle="{StaticResource GooglePolylineStyle}" 
            DataPointStyle="{StaticResource GoogleLineDataPointStyle}"
            MarkerHeight="10" MarkerWidth="10"
            Title="Visits"
            ItemsSource="{StaticResource TrafficInfo}"                                    
            IndependentValueBinding="{Binding Date}"
            DependentValueBinding="{Binding Visits}" />

And, here is the result:

GoogleLineDataPoint.jpg

There are a few things to notice here. Each DataPoint has the following properties you can use and display in your tooltip:

  • DependentValue
  • FormattedDependentValue
  • IndependentValue
  • FormattedIndependentValue

Each LineSeries can specify the DataPoint marker size using MarkerWidth and MarkerHeight.

Styling the chart

I want to remove the title and the ledger of the chart. There are two options to removing these items! You can create new styles for the title and the ledger that sets its visibility to Collapsed. (This trick also works if you don’t want DataPoint markers.)

XML
<Style x:Key="GoogleNoTitle" TargetType="datavis:Title">
    <Setter Property="Visibility" Value="Collapsed"/>
</Style>

Then, just set the TitleStyle and LedgerStyle properties on the chart:

XML
TitleStyle="{StaticResource GoogleNoTitle}"

The seconds method of removing these is to rather create a new ControlTemplate for the chart and remove them permanently!

XML
<Style x:Key="GoogleChart" TargetType="charting:Chart">
    <Setter Property="PlotAreaStyle">
        <Setter.Value>
            <Style TargetType="Grid">
                <Setter Property="Background" Value="White" />
            </Style>
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="charting:Chart">
                <Border
                Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}"
                Padding="10">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Grid Grid.Row="1" Margin="0,15,0,15">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="Auto"/>
                            </Grid.ColumnDefinitions>
                            <Grid x:Name="ChartArea" 
                                 Style="{TemplateBinding ChartAreaStyle}">
                                <Grid x:Name="PlotArea" 
                                      Style="{TemplateBinding PlotAreaStyle}" 
                                      Margin="0,0,0,0" >
                                    <Grid x:Name="GridLinesContainer" />
                                    <Grid x:Name="SeriesContainer" />
                                    <Border Margin="0,0,0,0" 
                                      BorderBrush="#FF919191" 
                                      BorderThickness="0,1,0,1"/>
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The new ControlTemplate merely removes the title and ledger! The last part of the chart we need to style are the axes. If you look at the Google chart, you will notice that the vertical grid lines indicate where a week starts; how difficult would this be?

Each chart has an Axes property, which can contain multiple axis! Here are some of the axis properties I used:

LabelStringFormatMMMM d, yyyyChanges the format of the labels
ShowGridLinesTrueShows the grid lines
ShowTickMarksTrueShows the grid line markers
ShouldIncludeZeroTrueScales from 0
IntervalTypeDaysIndicates what each unit on the axis is
Interval7Interval between points on the axis
IntervalOffset1Offset used in creating the axis
IntervalOffsetTypeDaysOffset type

Here is the markup:

XML
<charting:Chart.Axes>
    <charting:Axis Orientation="Horizontal" 
                   AxisType="DateTime" ShowGridLines="True" 
                   ShowTickMarks="True" LabelStringFormat="MMMM d, yyyy" 
                   IntervalType="Days" Interval="7" 
                   IntervalOffset="1" IntervalOffsetType="Days" 
                   Style="{StaticResource GoogleAxisStyle}" />
    <charting:Axis Orientation="Vertical" AxisType="Linear" ShowTickMarks="False" 
                   Interval="4000" IntervalType="Number" 
                   ShowGridLines="True" ShouldIncludeZero="True" 
                   Style="{StaticResource GoogleAxisStyle}"/>
</charting:Chart.Axes>

And that is it.

SilverlightChartDone.jpg

The Silverlight Toolkit Chart control is very flexible and powerful! Try it out, and you will be surprised at the endless ways you can style it!

If you found this article useful or interesting, please vote for it!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
South Africa South Africa
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy 5 Vote Pin
Anele 'Mashy' Mbanga12-Jan-17 4:29
professionalAnele 'Mashy' Mbanga12-Jan-17 4:29 
GeneralMy vote of 4 Pin
Ali Bagherzadeh23-Dec-14 2:54
Ali Bagherzadeh23-Dec-14 2:54 
GeneralMy vote of 1 Pin
Member 1076790620-May-14 4:40
Member 1076790620-May-14 4:40 
GeneralMy vote of 5 Pin
Fabián García28-Nov-12 8:08
Fabián García28-Nov-12 8:08 
General2010 Charting changed Pin
tomerhs9-Oct-10 21:54
tomerhs9-Oct-10 21:54 
SuggestionRe: 2010 Charting changed Pin
Member 1076790620-May-14 4:42
Member 1076790620-May-14 4:42 
GeneralDLL doesnot exist!! Pin
souidi abderrahman30-Aug-10 23:01
souidi abderrahman30-Aug-10 23:01 
GeneralRe: DLL doesnot exist!! Pin
Indivara4-Feb-11 14:10
professionalIndivara4-Feb-11 14:10 
GeneralMy vote of 5 Pin
Hariom Dubey7-Jul-10 19:23
Hariom Dubey7-Jul-10 19:23 
GeneralMy vote of 1 Pin
OBRon16-Dec-09 8:51
OBRon16-Dec-09 8:51 
GeneralMore ToolTip Properties Pin
Member 7107482-Oct-09 17:05
Member 7107482-Oct-09 17:05 
Hi,
I bind to a collection of Business Objects and I wanted to show properties of the bound item in the tooltip.   I finally worked out you can access all the properties of the bound item, not just the properties you mentioned. For example: say I was binding to a list of OrderItems, I can use this to get show the Client of the Order

<ContentControl DataContext="{TemplateBinding DataContext}" Content="{Binding Order.Client}"
   ContentStringFormat="Client: {0}"/>

Hope it's useful Smile | :)
GeneralAxis.IntervalType property does not exist Pin
Takuan.Daikon24-Aug-09 18:12
Takuan.Daikon24-Aug-09 18:12 
GeneralRe: Axis.IntervalType property does not exist Pin
Takuan.Daikon24-Aug-09 18:18
Takuan.Daikon24-Aug-09 18:18 
GeneralLine colors dynamically Pin
zappingz28-Feb-09 1:54
zappingz28-Feb-09 1:54 
GeneralRe: Line colors dynamically Pin
rudigrobler1-Mar-09 19:03
rudigrobler1-Mar-09 19:03 
GeneralRe: Line colors dynamically Pin
Ramsdal4223-Sep-10 2:47
Ramsdal4223-Sep-10 2:47 
GeneralRe: Line colors dynamically [modified] Pin
maxuepeng21-Dec-10 15:08
maxuepeng21-Dec-10 15:08 
GeneralRe: Line colors dynamically Pin
Member 404292826-Apr-11 8:44
Member 404292826-Apr-11 8:44 
GeneralMy vote of 2 Pin
Richard Deeming10-Feb-09 8:07
mveRichard Deeming10-Feb-09 8:07 
GeneralRe: My vote of 2 Pin
rudigrobler10-Feb-09 22:34
rudigrobler10-Feb-09 22:34 
GeneralRe: My vote of 2 Pin
Hüseyin Tüfekçilerli17-Feb-09 1:55
Hüseyin Tüfekçilerli17-Feb-09 1:55 
GeneralRe: My vote of 2 Pin
DZaK831-Mar-09 12:19
DZaK831-Mar-09 12:19 
GeneralRe: My vote of 2 Pin
rudigrobler1-Mar-09 19:04
rudigrobler1-Mar-09 19:04 
GeneralI can't compile the Pin
Tawani Anyangwe10-Feb-09 4:34
Tawani Anyangwe10-Feb-09 4:34 
GeneralRe: I can't compile the Pin
rudigrobler10-Feb-09 22:37
rudigrobler10-Feb-09 22:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.