#174 – Predefined Brushes Are Already Frozen

All of the brushes in the predefined Brushes collection are already in a frozen state, meaning that they are read-only.  Being frozen means that they will perform more efficiently when using them to render graphical objects, since WPF doesn’t need to worry about notifying consumers of the brush when the brush changes.

Here’s an example, where we have two different labels, one painted with a brush created in XAML and one painted with a brush from the Brushes collection.

    <Window.Resources>
        <SolidColorBrush x:Key="tealBrush" Color="Teal"/>
    </Window.Resources>
    <StackPanel>
        <Label Name="lblWithTealBrush" Content="I use a SolidColorBrush created in Window.Resources" Foreground="{StaticResource tealBrush}"/>
        <Label Name="lblWithRedBrush" Content="I use Brushes.Red">
            <Label.Foreground>
                <x:Static Member="Brushes.Red"/>
            </Label.Foreground>
        </Label>
        <Button Content="Click Me" Width="100" Click="btnTest_Click"/>
    </StackPanel>

We can add code to check the frozen state of these two different brushes.

        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            SolidColorBrush tealBrush = (SolidColorBrush)lblWithTealBrush.Foreground;
            bool frozen = tealBrush.IsFrozen;    // frozen = false

            SolidColorBrush redBrush = (SolidColorBrush)lblWithRedBrush.Foreground;
            frozen = redBrush.IsFrozen;          // frozen = true
        }
Advertisements