Static VS Dynamic Resources in WPF
In WPF A resource can be referenced as either a static resource or a dynamic resource. This is done by using either the StaticResource Markup Extension or the DynamicResource Markup Extension. A markup extension is a feature of XAML whereby you can specify an object reference by having the markup extension process the attribute string and return the object to a XAML loader. For more information about markup extension behavior, see Markup Extensions and WPF XAML.
When you use a markup extension, you typically provide one or more parameters in string form that are processed by that particular markup extension, rather than being evaluated in the context of the property being set. The StaticResource Markup Extension processes a key by looking up the value for that key in all available resource dictionaries. This happens during loading, which is the point in time when the loading process needs to assign the property value that takes the static resource reference. The DynamicResource Markup Extension instead processes a key by creating an expression, and that expression remains unevaluated until the application is actually run, at which time the expression is evaluated and provides a value.
When you reference a resource, the following considerations can influence whether you use a static resource reference or a dynamic resource reference:
- The overall design of how you create the resources for your application (per page, in the application, in loose XAML, in a resource only assembly).
- The application functionality: is updating resources in real time part of your application requirements?
- The respective lookup behavior of that resource reference type.
- The particular property or resource type, and the native behavior of those types.
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.
So, Static resources are resolved at compile time, whereas dynamic resources are resolved at runtime. Use DynamicResources when the value of the resource could change during the lifetime of the Application. Use StaticResources when it’s clear that you don’t need your resource re-evaluated when fetching it – static resources perform better than dynamic resources.
