32

Many types in WPF derive from Freezable. It provides immutability to mutable POCO objects and allows for improved performance in certain situations.

So my question is, how can I freeze objects in XAML markup?

(Note that I have posted a similar but different question too).

2
  • Does this really improve performance? Is there a way to measure the differences between a WPF app without and with po:Freeze="True" set all over the place? May 14, 2022 at 21:32
  • @AlexandruDicu it can make a big difference depending upon what your so is doing. To verify, you'd need to get before and after CPU traces and compare them. May 14, 2022 at 23:01

2 Answers 2

45

To freeze a Freezable object declared in markup, you use the Freeze attribute defined in XML namespace http://schemas.microsoft.com/winfx/2006/xaml/presentation/options.

In the following example, a SolidColorBrush is declared as a page resource and frozen. It is then used to set the background of a button.

<Page 
  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" 
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:Ignorable="po">

  <Page.Resources>
    <!-- This brush is frozen -->
    <SolidColorBrush x:Key="MyBrush" po:Freeze="True" Color="Red" />
  </Page.Resources>

  <!-- Use the frozen brush -->
  <Button Background="{StaticResource MyBrush}">Click Me</Button>

</Page>

Source: Freezable Objects Overview

1
  • 2
    Shouldn't the last attribute be mc:Ignorable="po"?
    – CodeNaked
    Sep 6, 2011 at 19:06
14

Add this to your xaml namespace declarations:

xmlns:po="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="po"

then, in your freezable objects, include this attribute

po:Freeze="True"
2
  • Where does the 'mc' namespace come from? Aug 25, 2009 at 9:11
  • Oh, i think i missed that. Fixed it now.
    – Botz3000
    Aug 25, 2009 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.