wpfxamlfreezable

How to freeze Path Data


We have many complex Paths in our WPF application. An example would be:

<Path Data="M14.077,9.772C11.634,9.772 9.652,11.753 9.652,14.197 9.652,16.641 11.634,18.622 14.077,18.622 16.521,18.622 18.502,16.641 18.502,14.197 18.502,11.753 16.521,9.772 14.077,9.772 M28,12L28,16 24.085,16C23.84,17.369,23.325,18.643,22.592,19.763L25.313,22.485 22.485,25.314 19.791,22.62C18.668,23.383,17.383,23.924,16,24.189L16,28 12,28 12,24.163C10.638,23.88,9.378,23.322,8.274,22.554L5.514,25.314 2.686,22.485 5.504,19.668C4.802,18.57,4.306,17.331,4.068,16L0,16 0,12 4.144,12C4.427,10.722,4.943,9.533,5.656,8.485L2.686,5.515 5.514,2.686 8.513,5.684C9.558,5,10.734,4.499,12,4.236L12,0 16,0 16,4.21C17.285,4.456,18.48,4.946,19.545,5.626L22.485,2.686 25.313,5.515 22.431,8.397C23.176,9.467,23.718,10.685,24.008,12z" Fill="{TemplateBinding Foreground}" Height="12" Width="12" Stretch="Fill" VerticalAlignment="Center" HorizontalAlignment="Right"/>  

Most of our Control Templates require extensive use of vector graphics and multiple effect are applied on these paths.

For performance reasons, we want to freeze the Data of these paths since it won't be changed. This syntax we're using creates a StreamGeometry and assigns data to it. StreamGeometry is freezable but how can we freeze it in our xaml?


Solution

  • You can utilize the PresentationOptions:Freeze="True" attribute. You can read more about it here.

    Summary from MSDN:

    Sets the IsFrozen state to true on the containing Freezable element. Default behavior for a Freezable without the PresentationOptions:Freeze attribute specified is that IsFrozen is false at load time, and dependent on general Freezable behavior at runtime.

    Setting IsFrozen to true is exactly the same as calling Freeze() on an Freezable object.

    In your case, you need to set the PathGeometry to be frozen.

    <Path>
        <Path.Data>
            <PathGeometry PresentationOptions:Freeze="True"
                Figures="..." />
        </Path.Data>
    </Path>