Monday, December 8, 2008

[Silverlight 2, C#] Make a dashed border "move" [animate]

I was looking to make my newly dashed border on my rectangle look like it was "moving" [as you see commonly in some applications when selecting an item].

To do this I created a doubleanimation on the "StrokeDashOffset" property of the Rectangle.

<. UserControl.Resources .>
<. Storyboard x:Name="LassoAnimation" .>
<. DoubleAnimation
Storyboard.TargetName="lasso"
Storyboard.TargetProperty="StrokeDashOffset"
By="1"
To="8"
RepeatBehavior="Forever"
Duration="0:0:3"
SpeedRatio="3" .>
<. /DoubleAnimation .>
<. /Storyboard .>
<. /UserControl.Resources .>

...

<. Rectangle x:Name="lasso"
Stroke="Blue" StrokeThickness="1" StrokeDashArray="6,2"
StrokeDashOffset="0" / .>

In order for the animation to be smooth you need to set the "To" value to be the size of the dash plus the gap values. So in my example, 8.

Then, when I want the animation to start in my C# code, I set the correct width/height/top/left values for the rectangle and then call the LassoAnimation.Begin function and BAM! Moving dashed border!


.

No comments: