#175 – Freeze Graphical Objects That You Don’t Intend to Modify

For performance purposes, it’s best to freeze graphical objects (e.g. brushes) if you don’t intend to modify them.  You must also freeze an object if you intend to reference it from a thread other than the thread that created it.

You can freeze an object in code, using the Freeze method.

            // SolidColorBrush, created in XAML, not frozen
            bool frozen = tealBrush.IsFrozen;    // frozen = false

            if (tealBrush.CanFreeze)
                tealBrush.Freeze();

            frozen = tealBrush.IsFrozen;         // frozen = true

You can also freeze an object in XAML, when it is declared, with the addition of an XML namespace.

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:po="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
        Title="MainWindow" Height="350" Width="525" >
    <Window.Resources>
        <SolidColorBrush x:Key="tealBrush" Color="Teal" po:Freeze="True"/>
    </Window.Resources>
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: