Using StaticResources in WPF

Updated 8/29/2018 - Formatted 
 
Resources provide a simple way to reuse commonly defined objects and values. If we are defining the resource then we can use that resource a number of times. (Just like applying themes and css to web pages).
 
Resources are two types:
  1. Static Resource
  2. Dynamic Resource.
Static Resource - StaticResources are resolved at compile time. 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.
 
Dynamic Resource - DynamicResources are resolved at runtime. Use DynamicResources when the value of the resource could change during the lifetime of the Application.
 
I will show you an example of a Static Resource.
 
In my WPF application page I have one textbox and two ellipses. In Window.Resources I defined the SolidColorBrush and the Style properties
  1. <Window.Resources>  
  2. <SolidColorBrush x:Key="brush" Color="Green"></SolidColorBrush>  
  3. <SolidColorBrush x:Key="forbuttoncolor" Color="CadetBlue"></SolidColorBrush>  
  4.     <Style TargetType="Border" x:Key="background">  
  5.         <Setter Property="Background" Value="Orange"></Setter>  
  6.     </Style>  
  7.     <Style TargetType="TextBox" x:Key="TitleText">  
  8.         <Setter Property="Background" Value="White"/>  
  9.         <Setter Property="DockPanel.Dock" Value="Top"/>  
  10.         <Setter Property="FontSize" Value="14"/>  
  11.         <Setter Property="Foreground" Value="#4E87D4"/>  
  12.         <Setter Property="FontFamily" Value="Tahoma"/>  
  13.         <Setter Property="Margin" Value="50,50,50,0"/>  
  14.         <Setter Property="Width" Value="300"></Setter>  
  15.     </Style>  
  16. </Window.Resources>  
In above code you can observe x: Key attribute. x: Key uniquely identifies elements that are created and referenced in a XAML-defined dictionary.
 
Here I'm using above resources. Have a look at below code.
 
Syntax is :{ StaticResource x:keyName}
  1. <Grid>  
  2. <StackPanel>  
  3. <Border Style="{StaticResource background}">  
  4. <DockPanel Height="300" Width="500">  
  5. <TextBox Style="{StaticResource TitleText}" Height="28" Width="150"> </TextBox>  
  6. <Ellipse DockPanel.Dock="Left" HorizontalAlignment="Left" Height="73" Fill="{StaticResource brush}" Width="169"></Ellipse>  
  7. <Ellipse DockPanel.Dock="Right" HorizontalAlignment="Right" Width="149" Height="73" Fill="{StaticResource forbuttoncolor}"></Ellipse>  
  8. </DockPanel>  
  9. </Border>  
  10. </StackPanel>  
  11. </Grid>  
Result window looks like this.
 
 
In my very next article, I will explain you about Dynamic Resource.
 
Hope you like this article, let me know if you have any queries.