Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to freeze all freezable WPF objects?

I want to freeze all freezable object that are in a window.(to get better performance)

To do it I used several loop like this:

    foreach (Brush item in FindLogicalChildren<Brush>(myWin))
                  if( item != null && item.CanFreeze)item.Freeze();

    foreach (Transform item in FindLogicalChildren<Transform>(myWin))
                   if( item != null && item.CanFreeze)item.Freeze();

    foreach (Geometry item in FindLogicalChildren<Geometry>(myWin))
                   if( item != null && item.CanFreeze)item.Freeze();

But it does not work.

How to call Freeze() on any freezable WPF object?

EDIT:

I just realized that the FindLogicalChildren not find anything, so it does not work.

EDIT2:

How to call Freeze() on any freezable objects by using ONE loop.

Please help me.

like image 511
Maria Avatar asked Sep 01 '25 16:09

Maria


1 Answers

You are correct, performance gets a real boost if everything is frozen.

You can do this in XAML.

In all Resource dictionaries, add the ice namespace:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:ice="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options">

Then, for every single XAML element that is freezable, freeze it. Examples:

    <SolidColorBrush ice:Freeze="True" x:Key="GlyphDisabledFillBrush" Color="{StaticResource Color_005}"/>
    <LinearGradientBrush ice:Freeze="True" x:Key="PendingOrderPositiveBrush"  EndPoint="8,8" StartPoint="0,0" SpreadMethod="Repeat"  MappingMode="Absolute">
        <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderLightPositiveColor}" Offset="0"/>
        <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderLightPositiveColor}" Offset="0.44"/>
        <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderDarkPositiveColor}" Offset="0.44"/>
        <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderDarkPositiveColor}" Offset="0.6"/>
        <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderLightPositiveColor}" Offset="0.6"/>
        <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderLightPositiveColor}" Offset="1"/>
    </LinearGradientBrush>

Benefits of not freezing elements

The only benefit of having non-frozen brushes is that we can potentially change the theme at runtime. If we are not worried about the theme change, then we can get a good performance boost by freezing all of the brushes. Freezing elements is also pretty much the only way that we can support multi threaded windows with separate dispatchers.

like image 50
Contango Avatar answered Sep 04 '25 15:09

Contango