views:

11106

answers:

1

When using resources such as brushes, templates and styles in WPF, they can be specified either as StaticResources

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

or as a DynamicResource

<ItemsControl ItemTemplate="{DynamicResource MyItemTemplate}"  />

Most of the times (always?), only one works and the other will throw exception during runtime. But I'd like to know why:

  • What is the main difference. Like memory or performance implications
  • Are there rules in WPF like "brushes are always static" and "templates are always dynamic" etc.?

I assume the choice between Static vs Dynamic isn't as arbitrary as it seems... but I fail to see the pattern.

+40  A: 

A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.

A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.

Phil Wright
What has to change before I need to use DynamicResource? Take a template for instance: i define it once but then of course triggers and stuff can change the content of the template but the template is still the same. Would StaticResource do here?
Isak Savo
Use StaticResource if the resource you are attaching to is defined in the XAML before its point of use and is not going to change for the lifetime of the application running. In that case you get better performance with StaticResource.
Phil Wright