Static Resources in WPF Application

Updated on     Kisan Patel

This tutorial will explain you what is resources, static resources, styles in WPF application with step-by-step example.

Resources in WPF allow you to reuse commonly defined objects and values in an application. They are mainly used to apply same style to more than one Window control.

To apply a style to more than one Window control, just define the resource in the main application file (App.xaml) and the style will be applied to controls by unique resource key as shown in below example:

App.xaml

<Application x:Class="WPFResourceDemo.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="MainWindow.xaml">
      <Application.Resources>
         <Style TargetType="Button" x:Key="GelButton">
             <Setter Property="Margin" Value="10,2,1,2"/>
             <Setter Property="HorizontalAlignment" Value="Left"/>
         </Style>
      </Application.Resources>
</Application>

wpf-resources-demo

Resources can be categorized as static or dynamic.

Static resources are resources that you do not intend to change after they are referenced the first time. These resources are always loaded on the creation of a window. You can reference a static resource by using the StaticResource markup extension, which processes the key whose value is looked up in the entire resource dictionary.

<Button Name="Button1" Height="50" Width="250" Style="{StaticResource GelButton}" Content="Button 1" />

You should define the resource dictionary before you reference the static resource.

For Example,

App.xaml

<Application x:Class="WPFResourceDemo.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="MainWindow.xaml">
      <Application.Resources>
         <Style TargetType="Button" x:Key="GelButton">
            <Setter Property="Margin" Value="10,2,1,2"/>
            <Setter Property="HorizontalAlignment" Value="Left"/>
         </Style>
         <SolidColorBrush x:Key="myGradientBrush" Color="Green"></SolidColorBrush>
         <SolidColorBrush x:Key="buttoncolor" Color="CadetBlue"></SolidColorBrush>
      </Application.Resources>
</Application>

In above code you can observe x: Key attribute. x: Key uniquely identifies elements that are created and referenced in a XAML-defined dictionary.

wpf-static-resource-demo


WPF

Leave a Reply