Resources in WPF and difference between Static Resource and Dynamic Resource
Posted by: Pravinkumar Dabade ,
on 6/15/2015,
in
Category WPF
Abstract: Understanding Resources in WPF including difference between static and dynamic resource
In WPF, Resources are objects which can be reused anywhere in a WPF application. For example styles, brushes, Bitmap images etc. can be used as resources in different places in your WPF application.
Here’s a list of place where your resources can be declared:
- As global application scope within the application App.xaml file
- As Window level scope within the
Resources
property of the current Window
- Within the
Resources
property of any FrameworkElement
or FrameworkContentElement
.
- Separate XAML resource file.
Here’s a diagrammatic representation of the places where resources can be declared:
As seen here, WPF resources can be declared at application level in the App.xaml file. You can also declare WPF Resources at Window/User Control level or declare them at panel level.
In case your resources are growing, then you can declare them in a separate file called as Resource Dictionary which you can refer at application level or any other level which you want to.
Let's see some examples of declaring resources at various levels -
Application Level Resources -
<Application.Resources>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1" x:Key="myBackgroundColor">
<GradientStop Offset="0" Color="Blue"/>
<GradientStop Offset="0.4" Color="Red"/>
<GradientStop Offset="0.7" Color="Purple"/>
<GradientStop Offset="1" Color="Yellow"/>
</LinearGradientBrush>
</Application.Resources>
Window Level Resources -
<Window.Resources>
<SolidColorBrush x:Key="textForeColorResource" Color="Blue"/>
</Window.Resources>
Panel Level Resources -
<Grid.Resources>
<BitmapImage x:Key="bitmapImageResource" UriSource="Koala.jpg" Rotation="Rotate90"/>
<clrType:String x:Key="titleResource">WelCome To www.dotnetcurry.com</clrType:String>
</Grid.Resources>
Please note that <clrType:String/> is coming from the imported namespace "System" -
xmlns:clrType="clr-namespace:System;assembly=mscorlib"
Utilizing WPF Resources
Let's see how to utilize these resources in our WPF Application. Resources declared in WPF application can be utilized in two different ways -
1. Static Resource - Static resources are the resources which you cannot manipulate at runtime. The static resources are evaluated only once by the element which refers them during the loading of XAML.
2. Dynamic Resource - Dynamic resources are the resources which you can manipulate at runtime and are evaluated at runtime. If your code behind changes the resource, the elements referring resources as dynamic resources will also change.
For example, if you use "bitmapImageResource" as a static resource, it will not change even if you manipulate the images source at runtime.
However let us say, if you are referring "textForeColorResource" as a dynamic resource and if your code behind logic changes the color at runtime, the elements which are referring this resource will get affected.
Note: Using Static Resources improves the performance of your WPF application. When you are using Dynamic Resources, make sure that the Element Properties must be Dependency Property. This behavior is because, DPs have Change Notification support implicitly implemented, which in turn updates your UI.
Let's see how to use these resources and change them at runtime -
<Window x:Class="WPFResources.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:clrType="clr-namespace:System;assembly=mscorlib"
>
<Window.Resources>
<SolidColorBrush x:Key="textForeColorResource" Color="Blue"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.Resources>
<BitmapImage x:Key="bitmapImageResource" UriSource="Koala.jpg" Rotation="Rotate90"/>
<clrType:String x:Key="titleResource">WelCome To www.dotnetcurry.com</clrType:String>
</Grid.Resources>
<StackPanel Orientation="Horizontal" Grid.Row="0">
<Image Name="firstImage" Source="{StaticResource ResourceKey=bitmapImageResource}" Height="100" Width="100" Stretch="Fill"/>
</StackPanel>
<TextBlock Text="WelCome" FontSize="18" Grid.Row="1" Foreground="{DynamicResource ResourceKey=textForeColorResource}"/>
<Button Height="50" Width="200" Background="{StaticResource ResourceKey=myBackgroundColor}" Content="{StaticResource ResourceKey=titleResource}" Name="clickMe" Click="clickMe_Click"/>
</Grid>
</Window>
Now let's write the following code which will change our SolidColorBrush to Red color on a button click event.
private void clickMe_Click(object sender, RoutedEventArgs e)
{
SolidColorBrush findSolidColorBrush= this.FindResource("textForeColorResource") as SolidColorBrush;
findSolidColorBrush.Color=Colors.Red;
this.Resources.Remove("textForeColorResource");
this.Resources.Add("textForeColorResource", findSolidColorBrush);
}
The output will look like the following-
Declare and refer resources in Resource Dictionary
To add a Resource Dictionary into your WPF application, right click the WPF project > add a Resource Dictionary.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1" x:Key="myAnotherBackgroundColor">
<GradientStop Offset="0" Color="Green"/>
<GradientStop Offset="0.4" Color="PeachPuff"/>
<GradientStop Offset="0.7" Color="Pink"/>
<GradientStop Offset="1" Color="Silver"/>
</LinearGradientBrush>
</ResourceDictionary>
Once you declare the resource dictionary, you can refer them at application level as shown below -
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MyResourcesDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Now apply the resource "myAnotherBackgroundColor" to button background and observe the changes.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Pravinkumar, works as a freelance trainer and consultant on Microsoft Technologies. He is having over 10 years of experience in IT and is also a Microsoft Certified Trainer(MCT). He has conducted various corporate trainings on all versions of .NET Technologies including .NET, SharePoint Server, Microsoft SQL Server, Silverlight, ASP.NET, Microsoft PerformancePoint Server 2007 (Monitoring). He is passionate about learning new technologies from Microsoft. You can contact Pravinkumar at dabade[dot]pravinkumar [attherate] gmail[dot]com