WPF: Static Resource

This entry is part 10 of 54 in the series Learn WPF

A resource is an object that can be reused in different places in the application.

This is somewhat similar to CSS style in HTML where one declaration can be applied to different selected elements.

In XAML, a StaticResource provides a quick way for us to store a value. For example a string or a double value.

To store the value, we need to add an x:Key to the XAML object so as to identify the resource in a resource dictionary.

It is best illustrated by using a simple example.

<Window x:Class="SayHi.MainWindow"
        Title="MainWindow" Height="350" Width="525">
        <sys:String x:Key="strSayHello">Say Hello!</sys:String>
        <sys:Double x:Key="strFontSize">36</sys:Double>
        <TextBlock HorizontalAlignment="Left" Margin="106,115,0,0" TextWrapping="Wrap" Text="{StaticResource strSayHello}" VerticalAlignment="Top" Height="74" Width="215" FontSize="{StaticResource strFontSize}"/>


In the above XAML file, line 4 was added to support String and Double namespaces.  xmlns means xml namespace.

Here we have stored a string and a double value in <Window.Resources>.  The x:key is for identifying the string or the double value.

To access the stored string, we have used Text=”{StaticResource strSayHello}”.  This type of declaration is also called Markup Extension in XAML.

The font size is also styled using StaticResource.  This is in a way, similar to using CSS to style HTML elements.





Series Navigation<< WPF: Grid
WPF: Data binding >>