如何冻结所有可冻结的 WPF 对象?

Mit*_*a M 2 c# wpf performance freeze

我想冻结窗口中的所有可冻结对象。(以获得更好的性能)

为此,我使用了几个这样的循环:

    foreach (Brush item in FindLogicalChildren<Brush>(myWin))
                  if( item != null && item.CanFreeze)item.Freeze();

    foreach (Transform item in FindLogicalChildren<Transform>(myWin))
                   if( item != null && item.CanFreeze)item.Freeze();

    foreach (Geometry item in FindLogicalChildren<Geometry>(myWin))
                   if( item != null && item.CanFreeze)item.Freeze();
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

如何调用Freeze()任何可冻结的 WPF 对象?

编辑:

我刚刚意识到FindLogicalChildren找不到任何东西,所以它不起作用。

编辑2:

如何使用 ONE 循环在任何可冻结对象上调用 Freeze()。

请帮我。

Con*_*ngo 6

你是对的,如果一切都被冻结,性能会得到真正的提升。

您可以在 XAML 中执行此操作。

在所有资源字典中,添加ice命名空间:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:ice="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options">
Run Code Online (Sandbox Code Playgroud)

然后,对于每个可冻结的 XAML 元素,冻结它。例子:

<SolidColorBrush ice:Freeze="True" x:Key="GlyphDisabledFillBrush" Color="{StaticResource Color_005}"/>
<LinearGradientBrush ice:Freeze="True" x:Key="PendingOrderPositiveBrush"  EndPoint="8,8" StartPoint="0,0" SpreadMethod="Repeat"  MappingMode="Absolute">
    <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderLightPositiveColor}" Offset="0"/>
    <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderLightPositiveColor}" Offset="0.44"/>
    <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderDarkPositiveColor}" Offset="0.44"/>
    <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderDarkPositiveColor}" Offset="0.6"/>
    <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderLightPositiveColor}" Offset="0.6"/>
    <GradientStop ice:Freeze="True" Color="{StaticResource PendingOrderLightPositiveColor}" Offset="1"/>
</LinearGradientBrush>
Run Code Online (Sandbox Code Playgroud)

不冻结元素的好处

使用非冻结笔刷的唯一好处是我们可以在运行时更改主题。如果我们不担心主题变化,那么我们可以通过冻结所有画笔来获得良好的性能提升。冻结元素几乎也是我们可以通过单独的调度程序支持多线程窗口的唯一方法。