Charles Petzold



Animated Polyline Interpolations in Silverlight

January 7, 2009
New York, N.Y.

In my Monday blog entry I used the CompositionTarget.Rendering event to animate an interpolation between two equally sized PointCollection objects.

I like CompositionTarget.Rendering: It takes all the guesswork out of deciding what period to use for timer animations. But whenever possible I think it's best to use the Timeline derivatives in Silverlight for animation. There are many advantages, not the least being that you can define them in XAML, and they are much more easily integratable with other animations.

That's the purpose of the PointCollectionInterpolator class that is part of the downloadable PolylineInterpolationDemo project.

PointCollectionInterpolator derives from FrameworkElement (I'll explain why shortly) and defines four dependency properties: Points1 and Points2 of type PointCollection, Progress of type double, and InterpolatedPoints, also of type PointCollection. Whenver one of the first three properties changes, the class executes the following code:

The PointCollectionInterpolator is instantiated as a resource (along with two PointCollection objects) in the Page.xaml file:

Notice that the PointCollectionInterpolator object is given both a resource x:Key and a Name. The x:Key allows the resource to be referenced in a binding (as usual) while the Name allows the Progress property to be animated by a DoubleAnimation. To celebrate the use of the DoubleAnimation for this job, I've also combined it with a ColorAnimation to change the polyline between green and red. You can see it running here:

PolylineInterpolationDemo.html

The availability of the Name property is the only reason I derived the PointCollectionInterpolator class from FrameworkElement rather than DependencyObject. You can't put an x:Name attribute in a resource but you can make use of Name. (I discussed issues with using x:Name and Name with WPF animations here and here.)

However, here's an interesting experiment you can perform: In PointCollectionInterpolator, change the base class from FrameworkElement to DependencyObject. The program compiles with a warning about "The property 'Name' does not exist on the type 'PointCollectionInterpolator'..." but the program works anyway! Silverlight sure has some strange voodoo inside!

The next step: Getting this polyline interpolation inside a ControlTemplate for a CheckBox. How disturbing it is to find that Silverlight templates don't have local resources....