Resources and Styles in WPF

Windows resources allow us to reuse defined values and objects. We can set the properties of multiple control at a time.

Here’s a list of place where your resources can be declared:

Lets see a very simple example of reusable string resource placing as Window Level Scope:

  1. Use the following namespace.
    1. xmlns:sys="clr-namespace:System;assembly=mscorlib"
  2. Declare the resource in Windows.Resources.
    1. <sys:String x:Key="strTitle">Pi-Techniques</sys:String>
  3. Now we can use above resource for binding data to controls.
    1. <TextBlock Text="{StaticResource strTitle}"/>

Code:

  1. <Window x:Class="WpfApplication.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:WpfApplication"
  7. xmlns:sys="clr-namespace:System;assembly=mscorlib"
  8. mc:Ignorable="d"
  9. Title="MainWindow" Height="350" Width="525">
  10. <Window.Resources>
  11. <sys:String x:Key="strTitle">Pi-Techniques</sys:String>
  12. </Window.Resources>
  13. <StackPanel>
  14. <TextBlock Text="{StaticResource strTitle}" FontSize="56" />
  15. <TextBlock>Welcome in "<TextBlock Text="{StaticResource strTitle}" />"!</TextBlock>
  16. </StackPanel>
  17. </Window>
Run Program

Example of reusable style

Styles in WPF are same as CSS in html.
  1. Declare new style in Windows Resources,
    1. <Window.Resources>
    2. <sys:String x:Key="strTitle">Pi-Techniques</sys:String>
    3. <Style TargetType="TextBlock">
    4. <Setter Property="Foreground" Value="DarkRed"/>
    5. <Setter Property="HorizontalAlignment" Value="Center"/>
    6. </Style>
    7. </Window.Resources>

    This style will automatically set for all TextBlocks in current page

    output

  2. We Can also Make object for specific Textblock
    1. <Window.Resources>
    2. <sys:String x:Key="strTitle">Pi-Techniques</sys:String>
    3. <Style TargetType="TextBlock">
    4. <Setter Property="Foreground" Value="DarkRed"/>
    5. <Setter Property="HorizontalAlignment" Value="Center"/>
    6. </Style>
    7. <Style x:Key="Headings" TargetType="TextBlock">
    8. <Setter Property="FontSize" Value="30"/>
    9. <Setter Property="Foreground" Value="Blue"/>
    10. <Setter Property="HorizontalAlignment" Value="Center"/>
    11. </Style>
    12. </Window.Resources>
    13. <StackPanel>
    14. <TextBlock Text="{StaticResource strTitle}" Style="{StaticResource Headings}"/>
    15. <TextBlock>Welcome in "<TextBlock Text="{StaticResource strTitle}" />"!</TextBlock>
    16. </StackPanel>
    run