wpffreezable

How do I create my own Freezable class?


I've tried MSDN but there is not an example for deriving from Freezable.

Update:

Yes in the MSDN there's an example with animations but it's too complicated. need something simpler to understand freezable.


Solution

  • Documentation

    In the MSDN documentation of the Freezable class, in the Remarks section, you can find the following paragraph:

    For information on using and creating your own Freezable objects, see Freezable Objects Overview.

    This overview contains a section Creating Your Own Freezable Class, which contains the theoretical background for what you want to do. To find an example, follow the link at the bottom of that section:

    For an example of a custom Freezable class, see the Custom Animation Sample.


    Example

    Since you specifically asked for a simple example, here is one (adapted from the MSDN page of Freezable.CreateInstanceCore). Remember the following sentence from the theory page:

    Every Freezable subclass must override the CreateInstanceCore method. If your class uses dependency properties for all its data, you're finished.

    Let's say we make a custom class MySimpleColor, which has exactly one boolean property IsRed. To make this class Freezable, we just have to override CreateInstanceCore:

    public class MySimpleColor : Freezable
    {
        // Here are your properties
        public static readonly DependencyProperty IsRedProperty = 
            DependencyProperty.Register("IsRed", typeof(Boolean), typeof(MySimpleColor));
    
        // CLR accessor of your property
        public bool IsRed {
            get { return (bool)GetValue(IsRedProperty); }
            set { SetValue(IsRedProperty, value); }
        }
    
        // All that's needed to make this Freezable
        protected override Freezable CreateInstanceCore() {
            return new MySimpleColor();      
        }
    }
    

    That's it. The code inherited from Freezable ensures that the Freezable methods such as Freeze() or Clone() work exactly as intended.