Resources in WPF

Resources property of Application class in WPF gets or sets a collection of application-scope resources such as styles and brushes. By setting Resources property on application level, you make these resources available to the entire application.

For example, this code snippet in Listing 1 adds a SolidColorBrush resource to the Application.

<Application x:Class="WPFSample.App"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

             StartupUri="Window1.xaml"

             Startup="App_Startup"

             ShutdownMode="OnLastWindowClose">

    <Application.Resources>

        <SolidColorBrush x:Key="YellowSolidBrush" Color="Yellow"></SolidColorBrush>

    </Application.Resources>

</Application>

Listing 1

Now I can access this resource on any Window or page of the application. For example, if I have a TextBlock in a Window, I can set Background property of this TextBlock to the SolidColorBrush defined in the Application by using StaticResource as you can see from Listing 2.

<TextBlock Background="{StaticResource YellowSolidBrush}" >Main Window</TextBlock>

Listing 2