Silverlight, ASP .NET, C#, AJAX, and all things Web 2.0

maandag 22 december 2008

Customizing the Labels on an Axis of the Silverlight Toolkit Chart

I've noticed a few posts on the Silverlight.NET forums concerning the customization of the X/Y-axis labels of the Silverlight Toolkit's Chart control: trying to get the text to wrap, trying to get the labels to display vertically instead of horizontally, ... 

Well, this is easy to do (working with the December release atm), but finding the right property to set can be quite a challenge. ;-)  So here you go: an Axis has an AxisLabelStyle-property, which you can bind to a style.  In this style, you can set all the properties you want, which will be applied to each and every label on your X- and/or Y-axis.

Eg, this piece of code will make sure the labels on my horizontal Axis (in this case, containing a DateTime) are rotated a bit, have a set width, and I also apply some formatting to the date:

   1: <Style x:Name="HorizontalLabelStyle" TargetType="Charting:AxisLabel">


   2:             <Setter Property="RenderTransform">


   3:                 <Setter.Value>


   4:                     <RotateTransform Angle="300"></RotateTransform>


   5:                 </Setter.Value>


   6:             </Setter>


   7:             <Setter Property="RenderTransformOrigin" Value="0.5,0.5"></Setter>


   8:             <Setter Property="StringFormat" Value="{}{0:dd/MM}"/>


   9:             <Setter Property="Width" Value="65"/>


  10: </Style>




In my chart, I set the AxisLabelStyle to this defined style:





   1: <Charting:Chart x:Name="chtChart">


   2:                    <Charting:Chart.Axes>


   3:                        <Charting:DateTimeAxis AxisLabelStyle="{StaticResource HorizontalLabelStyle}" 


   4:                            Orientation="Horizontal">


   5:                        </Charting:DateTimeAxis>


   6:                    </Charting:Chart.Axes>


   7: </Charting:Chart>




And that's it.  Further customization can off course be done, depending on your specific needs.  Happy charting! ;-)