如何在 XAML 中冻结从 Freezable 派生的 WPF 对象? [英] How can WPF objects deriving from Freezable be frozen in XAML?
问题描述
WPF 中的许多类型都源自 Freezable
.它为可变 POCO 对象提供了不变性,并允许在某些情况下提高性能.
Many types in WPF derive from Freezable
. It provides immutability to mutable POCO objects and allows for improved performance in certain situations.
所以我的问题是,如何冻结 XAML 标记中的对象?
So my question is, how can I freeze objects in XAML markup?
(请注意,我也发布了一个类似但不同的问题).
(Note that I have posted a similar but different question too).
推荐答案
要冻结在标记中声明的 Freezable
对象,请使用 XML 命名空间中定义的 Freeze
属性<代码>http://schemas.microsoft.com/winfx/2006/xaml/presentation/options.
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
.
在以下示例中,SolidColorBrush
被声明为页面资源并被冻结.然后它用于设置按钮的背景.
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>
来源:可冻结对象概述
这篇关于如何在 XAML 中冻结从 Freezable 派生的 WPF 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!