1
votes

My WPF application has several windows and I want to use the same background image for all of them. I've defined the bitmap and image brush in a resource dictionary as follows.

<BitmapImage x:Key="BackgroundImage" UriSource="/Resources/BackPlate.png"/>
<ImageBrush x:Key="BackgroundBrush" ImageSource="{StaticResource BackgroundImage}" TileMode="Tile" ViewportUnits="Absolute" Viewport="0,0,128,128"/>

When I set the background property in the Window description, the background changes successfully in Visual Studio, but when I run the application, I get a parsing exception, I assume because the window resources haven't actually been read yet?

<Window x:Class="MyApp.Test"
...
    Background="{StaticResource BackgroundBrush}">
<Window.Resources>
...

Is there another way to specify the background after the resources have been read? I've tried the Window.Background approach, but I can't figure out how to get it to work w/o specifying the whole image brush definition.

 <Window.Background>
    <ImageBrush ?>
</Window.Background>

Is there a way to specify the image brush by reference when using this approach?

1
Have you tried a Style Template with the background added to it to be inherited to each instance? What's the exception you get?Chris W.
The exception is "A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll Additional information: 'Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '5' and line position '35'."user7134019

1 Answers

1
votes

It should work provided that you merge the ResourceDictionary into your App.xaml file:

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="YourResourceDictionary.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>