Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between StaticResource and DynamicResource in WPF?

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.

like image 516
Isak Savo Avatar asked Oct 14 '08 11:10

Isak Savo


People also ask

What is Dynamic resource WPF?

Dynamic ResourceThe concept is the same as data binding in WPF if the value of the bound property is changed. So is the value on UI. Change XAML as follows: added a new button. <Window x:Class="A.MainWindow"

What is a dynamic resource?

Dynamic resources are resources that move along an assigned path network and may transport entities between locations as a forklift would. They may also need to process entities at several locations, such as an operator performing tasks at more than one location.

What is ResourceDictionary WPF?

In Extensible Application Markup Language (XAML), the ResourceDictionary class is typically an implicit collection element that is the object element value of several Resources properties, when given in property element syntax. For details on implicit collections in XAML, see XAML Syntax Terminology.


1 Answers

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.

like image 109
Phil Wright Avatar answered Oct 19 '22 03:10

Phil Wright