#174 – Predefined Brushes Are Already Frozen
January 2, 2011 2 Comments
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 }
Hi! Interesting post.
One question: Can I use personalized brushes like
to become Freezen?
Thanks in advance!
Alex, are you asking whether you can freeze brushes that you create? The answer is–yes, you can. See https://wpf.2000things.com/2011/01/03/175-freeze-graphical-objects-that-you-dont-intend-to-modify/