WPF
StaticResource
DynamicResource
XAML
.NET

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Windows Presentation Foundation (WPF), resources play a significant role in managing the look and feel of your application. These resources can be defined and reused across the application to ensure consistency and reduce redundancy. Two primary ways to reference resources in XAML are StaticResource and DynamicResource. Both have their unique use cases and implications, which are crucial to understand for effective WPF development.

Technical Explanation

StaticResource

StaticResource is used to fetch resources defined in XAML at compile time. The resource is resolved at the time the XAML is compiled, which implies that the resource lookup happens only once. This results in a slight performance boost because the application doesn't have to resolve the resource at runtime; however, it comes with the trade-off that the resource cannot change after the application starts running.

Example:

xml
1<Window x:Class="WpfApp.MainWindow"
2        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4        Title="MainWindow" Height="200" Width="400">
5
6    <Window.Resources>
7        <SolidColorBrush x:Key="MyBrush" Color="Blue"/>
8    </Window.Resources>
9
10    <Grid Background="{StaticResource MyBrush}"/>
11</Window>

In the above example, MyBrush is a static resource defined within the window's resources. It is used to set the background color of a grid. Once the application is running, changing MyBrush's color in the resources will not affect the grid's background.

DynamicResource

DynamicResource is used to reference resources that might change during the application's runtime. Unlike StaticResource, DynamicResource performs its lookup at runtime. This dynamic lookup allows for changes to the resource dictionary to be observed and applied.

Example:

xml
1<Window x:Class="WpfApp.MainWindow"
2        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4        Title="MainWindow" Height="200" Width="400">
5
6    <Window.Resources>
7        <SolidColorBrush x:Key="MyBrush" Color="Blue"/>
8    </Window.Resources>
9
10    <Grid Background="{DynamicResource MyBrush}"/>
11
12    <!-- Code-behind or command that updates MyBrush -->
13    <!-- (e.g., Resources["MyBrush"] = new SolidColorBrush(Colors.Red);) -->
14</Window>

In this example, any changes made to MyBrush during runtime, such as changing its color property through code-behind, will automatically update the grid's background.

Key Differences

FeatureStaticResourceDynamicResource
Lookup TimeCompile timeRuntime
PerformanceFaster (one-time resolution)Slower (multiple lookups, depending on changes)
Resource ChangesNot responsive to changes after application startupResponds to changes made to the resources at runtime
Use CaseSuitable for resources that do not change, such as static styles or constantsSuitable for resources expected to change during runtime, such as themes or locale switches
XAML Syntax&#123;StaticResource ResourceKey&#125;&#123;DynamicResource ResourceKey&#125;

Additional Considerations

Resource Dictionary

Both StaticResource and DynamicResource rely on WPF's resource dictionary to locate resources. A resource dictionary can be defined at various levels such as Application, Window, or Control level. The hierarchical search is performed for resources where a resource declared at the local level will be prioritized over one declared globally.

Resource Dictionary Merging

DynamicResource is particularly useful when dealing with merged resource dictionaries, as it can handle changes dynamically as different dictionaries override or prepend resources.

Memory Considerations

While using DynamicResource, care must be taken regarding memory usage. Since dynamic resources require the runtime to monitor changes and propagate them, they can introduce additional overhead compared to static resources.

Themes and Localization

Applications that support multiple themes or locales will benefit significantly from DynamicResource. For example, swapping a resource dictionary to change the application’s theme doesn't require reloading of the application if DynamicResource is employed.

Limitations

  • StaticResource cannot be used with resources that are recursively defined.
  • DynamicResource may introduce some lag in responsiveness due to runtime lookup, especially if used extensively in high-latency scenarios.

Understanding the differences between StaticResource and DynamicResource allows developers to make informed choices about their application's performance and flexibility. Balancing between static and dynamic references based on the application requirements and scenarios is critical to optimizing both performance and user experience.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.