如何从Freezable派生的WPF对象在XAML中被冻结?

Dre*_*kes 28 wpf performance xaml freezable

WPF中的许多类型都源于Freezable.它为可变POCO对象提供了不变性,并允许在某些情况下提高性能.

所以我的问题是,如何在XAML标记中冻结对象?

(请注意,我也发布了类似但不同的问题).

CSh*_*per 42

要冻结Freezable标记中声明的对象,请使用FreezeXML命名空间中定义的属性http://schemas.microsoft.com/winfx/2006/xaml/presentation/options.

在以下示例中,a SolidColorBrush被声明为页面资源并被冻结.然后用它来设置按钮的背景.

<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>
Run Code Online (Sandbox Code Playgroud)

来源:Freezable Objects概述

  • 最后一个属性不应该是`mc:Ignorable ="po"`? (2认同)

Bot*_*000 12

将其添加到xaml名称空间声明中:

xmlns:po="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="po"
Run Code Online (Sandbox Code Playgroud)

然后,在您的freezable对象中,包含此属性

po:Freeze="True"
Run Code Online (Sandbox Code Playgroud)