I attempted to create a dashed line today in Silverlight and quickly found myself searching for examples on how to do so. In ASP.NET I'm used to setting a BorderStyle property to do so. With Silverlight, we have to do a little more work. I will show how you can create a dashed line in Silverlight via XAML and I will also show you how to do this programmatically. This is what our final Silverlight application will look like once we are finished.
"StrokeDashArray" is the property which we use to define our dashes. This property indicates the pattern of dashes and spaces between the dashes. The first value is the width of the dash and the second value is the space between the dashes.
<Line x:Name="Line1" X1="20" Y1="10" X2="300" Y2="10" Stroke="#4284B0" Canvas.Top="10" StrokeDashArray="4 2"/>
This is how you would define a dashed line in XAML. Here we have a line where each dash is 4 pixels wide and has a 2 pixel spacer between each dash. Next, I will show you how you can create a dashed line programmatically.
Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Dim dashArray As DoubleCollection = New DoubleCollection()
Me.Line2.StrokeDashArray = dashArray
Here we define our dashed line programmatically. You see that I create a dashArray object first of a DoubleCollection type. I fill it with a 10 and a 5 (10 pixel wide dash with 5 pixel spacers in between each dash). I then assign my line's StrokeDashArray property to my dashArray DoubleCollection.
SilverlightDashedLine_Soln.zip (537.26 kb)