Static And Dynamic Resources In WPF

Introduction

 
In this article, you will learn how to define static & dynamic resources, how to utilize them in an application or single-screen wide, and how to load multiple resource files together. 
 
What are Resources?
 
Resources are stored temporarily somewhere so that we can reuse them when we need them.

Just like cached memory in the CPU. It stores frequently used data in the cache for faster access, and it loads data from the cache instead of fetching it from RAM or HDD.
 
The same concept exists in WPF: we store data in UI (Screen) i.e. in the same XAML or some common XAML from where other UI pages can load its data.

Advantages
  1. Re-usability, just define it once in a common file and use it in multiple XAMLs.
  2. Store data locally, i.e. in the same window, if usage scope is the same window or in some common file is usage scope is global i.e. entire application.
  3. Or you can define it inside a panel such as Grid, Stack panel, etc. 
So let's get down to it.

WPF has 2 types of resources.
  1. Static Resource
  2. Dynamic Resource 
How to declare: here we can declare Resources as per their usage scope. There are 4 ways:

Window level resources:
  1. <Window.Resources>    
  2.       <Thickness x:Key="MarginTop">0 5 0 0</Thickness>    
  3. </Window.Resources>     
Panel level resources:
  1. <Grid.Resources>    
  2.      <Thickness x:Key="MarginTR">0 5 5 0</Thickness>    
  3. </Grid.Resources>     
Application-level resources
 
Go to the application's App.Xaml 
  1. <Application.Resources>    
  2.            <Thickness x:Key="MarginTR">0 5 5 0</Thickness>    
  3. </Application.Resources>     
Resource Dictionary

Right-click on a project and add a resource dictionary:
 
Static And Dynamic Resources In WPF
  1. <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
  2.                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
  3.                     xmlns:local="clr-namespace:A">    
  4.     <Thickness x:Key="MarginTR">0 5 5 0</Thickness>    
  5. </ResourceDictionary>    
Once you are finished with defining a ResourceDictionary, you can add it inside a App.xaml if you wanted to use it across the application.

Edit App.Xaml as follows.

The advantage here is that you can add multiple resource dictionaries to an application. 
  1. <Application x:Class="A.App"    
  2.              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
  4.              xmlns:local="clr-namespace:A"    
  5.              StartupUri="MainWindow.xaml">    
  6.     <Application.Resources>    
  7.         <ResourceDictionary>    
  8.             <ResourceDictionary.MergedDictionaries>    
  9.                 <ResourceDictionary Source="ResourceDictionaryMargins.xaml"/>    
  10.             </ResourceDictionary.MergedDictionaries>    
  11.         </ResourceDictionary>    
  12.     </Application.Resources>    
  13. </Application>     
 If you want to keep your scope to your Window or UserControl, then update Window.Resources.
  1. <Window.Resources>    
  2.         <ResourceDictionary>    
  3.             <ResourceDictionary.MergedDictionaries>    
  4.                 <ResourceDictionary Source="ResourceDictionaryMargins.xaml"/>    
  5.             </ResourceDictionary.MergedDictionaries>    
  6.         </ResourceDictionary>    
  7. </Window.Resources>     
How to Use
 
It's very simple, just use StaticResource or DynamicResource tag, as per the application's requirements.
  1. Margin="{StaticResource MarginTop}" 
Let's go ahead and create a WPF application.
 
Static Resource
 
It will not change once it's assigned and they are applied at the compiled time only.
 
Add 2 static resources, one for button's background & another for the button's border. 
  1. <Window x:Class="A.MainWindow"    
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
  4.         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    
  5.         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    
  6.         xmlns:local="clr-namespace:A"    
  7.         mc:Ignorable="d"    
  8.         Title="MainWindow" Height="150" Width="300">    
  9.     <Window.Resources>    
  10.         <SolidColorBrush x:Key="SolidAquamarine" Color="Aquamarine"/>    
  11.         <SolidColorBrush x:Key="SolidBlack" Color="Black"/>    
  12.     </Window.Resources>    
  13.     <Grid x:Name="MainGrid">    
  14.         <Button x:Name="SubmitButton"    
  15.                Background="{StaticResource SolidAquamarine}"    
  16.                BorderBrush="{StaticResource SolidBlack}"    
  17.                Content="Submit"    
  18.                Height="20"    
  19.                Width="100"/>    
  20.     </Grid>    
  21. </Window>     
Static And Dynamic Resources In WPF
 
As you can see, the .NET framework does not wait until code execution, you can see changes at compile-time only.
 
Dynamic Resource
 
It will change even after its being used. The 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.
  1. <Window x:Class="A.MainWindow"    
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
  4.         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    
  5.         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    
  6.         xmlns:local="clr-namespace:A"    
  7.         mc:Ignorable="d"    
  8.         Title="MainWindow" Height="150" Width="300">    
  9.     <Window.Resources>    
  10.         <SolidColorBrush x:Key="SolidAquamarine" Color="Aquamarine"/>    
  11.         <SolidColorBrush x:Key="SolidBlack" Color="Black"/>    
  12.     </Window.Resources>    
  13.     <Grid x:Name="MainGrid">    
  14.         <StackPanel VerticalAlignment="Center">    
  15.         <Button x:Name="SubmitButton"    
  16.                Background="{StaticResource SolidAquamarine}"    
  17.                BorderBrush="{StaticResource SolidBlack}"    
  18.                Content="Submit"    
  19.                Height="20"    
  20.                Width="100"/>    
  21.         <Button x:Name="ExitButton"    
  22.                Background="{DynamicResource ButtonExitBackgroundColor}"    
  23.                BorderBrush="{DynamicResource ButtonExitBorderColor}"    
  24.                Margin="0 10 0 0"    
  25.                Content="Submit"    
  26.                Height="20"    
  27.                Width="100"/>    
  28.         </StackPanel>    
  29.     </Grid>    
  30. </Window>    
Also, add 2 resources in the code behind.
  1. using System.Drawing;  
  2. using System.Windows;  
  3. using System.Windows.Media;  
  4.   
  5. namespace A  
  6. {  
  7.     /// <summary>  
  8.     /// Interaction logic for MainWindow.xaml  
  9.     /// </summary>  
  10.     public partial class MainWindow : Window  
  11.     {  
  12.         public MainWindow()  
  13.         {  
  14.             InitializeComponent();  
  15.             this.DataContext = new MainWindowViewModel();  
  16.             this.Resources["ButtonExitBackgroundColor"] = new SolidColorBrush(Colors.LightGray);  
  17.             this.Resources["ButtonExitBorderColor"] = new SolidColorBrush(Colors.Black);  
  18.         }  
  19.     }  
  20. }  
 Static And Dynamic Resources In WPF
 
Now, have a look. Color is not applied on the 2nd button at compile-time, as the .NET framework resolves it at runtime.

Now run the project to see the magic.
 
Static And Dynamic Resources In WPF
 
Hurray! Color has been applied on the 2nd button as expected.

You can define DynamicResource in XAML as well, but it will resolve at runtime only.
  1. <StackPanel VerticalAlignment="Center">    
  2.        <Button x:Name="SubmitButton"    
  3.               Background="{StaticResource SolidAquamarine}"    
  4.               BorderBrush="{StaticResource SolidBlack}"    
  5.               Content="Submit"    
  6.               Height="20"    
  7.               Width="100"/>    
  8.        <Button x:Name="ExitButton"    
  9.               Background="{DynamicResource SolidAquamarine}"    
  10.               BorderBrush="{DynamicResource SolidBlack}"    
  11.               Margin="0 10 0 0"    
  12.               Content="Submit"    
  13.               Height="20"    
  14.               Width="100"/>    
  15. </StackPanel>     
I hope this article has cleared your confusion between static and dynamic resources in WPF.
 
Please apply them to achieve reusability in your projects.
 
Happy Coding!
 
If you have any queries, feel free to connect with me @