Wednesday, March 30, 2011

StaticResource, DynamicResource, x:Static – what’s all this about?

So, you know to write very complicated things in XAML code, but, really, do you know what’s the difference between static and dynamic resource? Do you know what’s really x:Static means? We’ll try today to understand differences and things we can do with this stuff. All those are markup extensions. Let’s start from the very beginning – MSDN
A markup extension can be implemented to provide values for properties in attribute syntax, properties in property element syntax, or both.

StaticResource – Provides a value for a XAML property by substituting the value of an already defined resource
DynamicResource - Provides a value for a XAML property by deferring that value to be a runtime reference to a resource. A dynamic resource reference forces a new lookup each time that such a resource is accessed.

I can not tell more clear then this statement. If you want to reuse something already exists – use StaticResource, if it’s changing – DynamicResource. So StaticResource is restrictive resource, when DynamicResource is not. So, other words, if you need only properties to be changed, use StaticResource, if whole object changing – use DynamicResource . The best example for this is following code

      <TextBlock Text="This is Active caption color" Background="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
      <TextBlock Text="This is not Active caption color" Background="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}">
        <TextBlock.Resources>
          <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Yellow" />
        </TextBlock.Resources>
      </TextBlock>
      <TextBlock Text="This is Active caption color" Background="{StaticResource {x:Static SystemColors.HighlightBrushKey}}"/>
      <TextBlock Text="This is also Active caption color" Background="{StaticResource {x:Static SystemColors.HighlightBrushKey}}">
        <TextBlock.Resources>
          <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Yellow" />
        </TextBlock.Resources>
      </TextBlock>
The result is following
..
As you can see, I completely change HighlightBrush object by using local resources. This works if the resource set as dynamic, but wont if static.
That’s the reason, that you can not bind to DynamicResource, only to StaticResource properties or method results. Data binding engine can not be in peace with changing objects.
So, what is x:Static? It’s XAML-defined Markup extension. There are some of them x:Type, x:Static x:Null and x:Array.
x:Static – Produces static values from value-type code entities that are not directly the type of a property’s value, but can be evaluated to that type