使用资源字典中的WPF背景

时间:2017-03-14 17:39:16

标签: wpf xaml

我的WPF应用程序有几个窗口,我想为所有窗口使用相同的背景图像。我已经在资源字典中定义了位图和图像画笔,如下所示。

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

当我在Window描述中设置background属性时,后台在Visual Studio中成功更改,但是当我运行应用程序时,我得到一个解析异常,我假设因为窗口资源尚未被实际读取?

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

在读取资源后是否有另一种指定背景的方法?我已经尝试过Window.Background方法,但我无法弄清楚如何使用它来指定整个图像画笔定义。

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

使用这种方法时,有没有办法通过引用指定图像画笔?

1 个答案:

答案 0 :(得分:1)

只要您将ResourceDictionary合并到App.xaml文件中

,它就可以正常工作
<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>