Charles Petzold

FreezableCollection Tip

March 19, 2007
New York, N.Y.

Throughout the WPF graphics system are collection classes that derive from Freezable by way Animatable. These are generally collections of objects that also derive from Freezable or Animatable. These freezable collection classes fire change notifications whenever items are added to or removed from the collection, of course, but also when a dependency property of any item within the collection changes. This is an extremely powerful mechanism.

TransformCollection, for example, derives from Freezable and Animatable. It fires notifications whenever one of the transforms in the collection changes (for example, though a data binding or animation), allowing the composite transform to be re-calculated and the graphics object to reflect that change.

If you ever need a custom WPF collection class that derives from Freezable and Animatable you will be overjoyed to discover the generic FreezableCollection<T> class, where T derives from DependencyObject. This class will save you a lot of work.

After discovering FreezableCollection<T> you might be tempted to define your custom freezable collection class as simply as this:

But watch out! The cardinal rule for classes that derive from Freezable is this: Override the CreateInstanceCore method! Normally you only need to call the default constructor and return the result, but there are cases in which failure to override CreateInstanceCore will cause problems that might leave you baffled for days! (Does that sound like the voice of experience or what?) Here's a much better custom freezable collection class: