xamlbindingfreezable

Does Freezable or Binding take precedence in WPF?


So, System.Windows.Media.Brushes are freezable. This means that if you call .Freeze() on a Brush, it becomes unmodifiable. This improves performance.

In WPF, you can use Bindings are a way for properties to update when other properties change.

So, what happens when I create a Frozen brush, but bind the color? Does the freezing take precedence or the Binding?

<Window x:Class="WpfApplication4.MainWindow"
    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"
    Title="MainWindow" Height="350" Width="525" 
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    Foreground="Green">
<Window.Resources>
    <SolidColorBrush x:Key="foregroundCopy" Color="{Binding Foreground}" po:Freeze="True"/>
</Window.Resources>

    <Rectangle Fill="{StaticResource foregroundCopy}"/>

</Window>

I tried it out, and the rectangle's color updates when I change the Window's Foreground. Does this mean you can modify a Brush's Color Property despite it being frozen? Or is the color frozen as a binding? How does this affect the performance gains of freezing an object?


Solution

  • The Binding takes precedence.

    I tried modifying the brush's color directly from the code behind, and it allowed me to do so (so it wasn't frozen.)

    Then I tried freezing the Brush from the code behind, and it threw an error saying "This freezable cannot be frozen." My guess is that the binding is causing the same error in XAML, but it's being caught.