How to use application resources (WPF .NET)

This example demonstrates how to use application-defined resources. Resources can be defined at the application level, generally through the App.xaml or Application.xaml file, whichever one your project uses. Resources that are defined by the application are globally scoped and accessible by all parts of the application.


The Desktop Guide documentation for .NET 6 and .NET 5 (including .NET Core 3.1) is under construction.


The following example shows an application definition file. The application definition file defines a resource section (a value for the Resources property). Resources defined at the application level can be accessed by all other pages that are part of the application. In this case, the resource is a declared style. Because a complete style that includes a control template can be lengthy, this example omits the control template that is defined within the ContentTemplate property setter of the style.

    <Style TargetType="Border" x:Key="FancyBorder">
        <Setter Property="Background" Value="#4E1A3D" />
        <Setter Property="BorderThickness" Value="5" />
        <Setter Property="BorderBrush">
                    <GradientStop Offset="0.0" Color="#4E1A3D"/>
                    <GradientStop Offset="1.0" Color="Salmon"/>

The following example shows a XAML page that references an application-level resource from the previous example. The resource is referenced with a StaticResource Markup Extension that specifies the unique resource key for the resource. The resource "FancyBorder" isn't found in the scope of the current object and window, so the resource lookup continues beyond the current page and into application-level resources.

<Border Style="{StaticResource FancyBorder}">
    <StackPanel Margin="5">
        <Button>Button 1</Button>
        <Button>Button 2</Button>
        <Button>Button 3</Button>
        <Button>Button 4</Button>

See also