Pages

Sunday 5 October 2008

How are StaticResource and DynamicResource different


This was copied from http://wpfxaml.spaces.live.com/blog/cns!97DD5FD32788695B!142.entry for my own easy reference

Everyone one knows that StaticResource let’s one set a property of an element once.
If the Desktop Color is changed while the element’s application is running, the element keeps its original color:


    <Button>
      <Button.Background>
        <SolidColorBrush Color="{StaticResource {x:Static SystemColors.DesktopColorKey}}" />
      </Button.Background>
      Hello
    </Button>


On the other hand, if the element’s color is set using a DynamicResource, it changes when the Desktop Color changes:

    <Button>
      <Button.Background>
        <SolidColorBrush Color="{DynamicResource {x:Static SystemColors.DesktopColorKey}}" />
      </Button.Background>
      Hello
    </Button>

Why is that? The answer comes from the way these two Resource finders work:

    1.       StaticResource – Finds the resource given in by the ResourceDictionary key, and keeps the resource value;
    2.       DynamicResource – Finds the resource in the ResourceDictionary and keeps the key.

So, it is simple, really.
Since DynamicResource keeps the resource Key instead of the resource value, every event change fired from the resource lets the DynamicResource know that its value has changed.
This is why the DynamicResource reacts to the resource changes, while the StaticResource can’t know the resource has changed, since it only keeps the resource’s final value.

No comments: