Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

WPF: StaticResource vs DynamicResource

0.00/5 (No votes)
7 Jun 2012 1  
The differences between StaticResource and DynamicResource.

Logical resources allow you to define objects in XAML, which are not part of visual tree but can be used in your user interface. One of the examples of a logical resource is Brush, which is used to provide a color scheme. Generally those objects are defined as resources, which are used by multiple elements of the applications.

<Window.Resources>
    <RadialGradientBrush x:Key="myGradientBrush">
        <GradientStop Color="Green" Offset="0"/>
        <GradientStop Color="Blue" Offset="2"/>
    </RadialGradientBrush>
</Window.Resources>

Now, above declared resource could be used as either static or dynamic resource. One point to remember is that, when using static resources, it should be first defined in XAML code, before it can be referred. Static and Dynamic resources can be used as:

<Grid Background="{StaticResource myGradientBrush}"></Grid>

or

<Grid Background="{DynamicResource myGradientBrush}"></Grid>

The difference between StaticResource and DynamicResource lies in how the resources are retrieved by the referencing elements. StaticResource are retrieved only once by the referencing element and used for entire life of the resource. On the other hand, DynamicResource are acquired every time the referenced object is used.

Putting it in simpler way, if the color property of RadialGradientBrush is changed in code to Orange and Pink, then it will reflect on elements only when resource is used as DynamicResource. Below is the code to change the resource in code:

RadialGradientBrush radialGradientBrush = new RadialGradientBrush( Colors.Orange, Colors.Pink);
this.Resources["myGradientBrush"] = radialGradientBrush;

The demerit of DynamicResource is that it reduces application performance because resources are retrieved every time they are used. The best practice is to StaticResource use until there is a specific reason to use DynamicResource.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here