#52 – Defining and Using Application-Scoped Resources

WPF resources can be associated with the main Application object, if you want them available throughout the application.

You can define application-scoped resources in the main Application XAML file (App.xaml).  In the example below, we define a green brush.

<Application x:Class="WpfApplication.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml" Startup="Application_Startup" >
    <Application.Resources>
        <SolidColorBrush x:Key="greenBrush"  Color="Green"/>
    </Application.Resources>
</Application>


To use this resource, you use a XAML extension to reference a static resource.  In the example below, we set the background color of a button in our main window to the green brush that we defined above.

<Window x:Class="WpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="224" Width="334">
    <Grid>
        <Button Content="Button" Background="{StaticResource greenBrush}"
                Height="23" HorizontalAlignment="Left" Margin="60,57,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>
</Window>

Advertisements