WPF系列教程(二十七):资源字典Resource和ResourceDictionary,用资源字典添加图像画刷

在多个项目之间共享资源,可创建资源字典,一个资源字典就是一个用于存储资源的xaml文件。
项目源码

创建资源字典

右键项目,添加资源字典。
在资源字典中添加两个图像画刷的资源:

<ImageBrush x:Key="TileBrush1" TileMode="Tile" Viewport="0 0 32 22" ViewportUnits="Absolute" ImageSource="/true.jpg" Opacity="0.3">
    <!--ViewPort表示从0,0位置开始,大小32-->
</ImageBrush>
<ImageBrush x:Key="TileBrush2" TileMode="Tile" Viewport="0 0 32 22" ViewportUnits="Absolute" ImageSource="/edc4afe6c0ffc1e2.jpg" Opacity="0.3">
    <!--ViewPort表示从0,0位置开始,大小32-->
</ImageBrush>

使用资源字典

将定义的资源字典加入到应用程序资源中,在App.xaml的资源集合中添加资源字典:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries><!--合并字典-->
            <ResourceDictionary Source="Dictionary1.xaml">
            </ResourceDictionary>
            <ResourceDictionary Source="Dictionary2.xaml">
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

在按钮中使用画刷背景:

<Button Name="btn1" Margin="5" Padding="5" FontSize="14" Content="Button1" Background="{DynamicResource TileBrush1}">
</Button>

在这里插入图片描述
要使用资源字典,就要在应用程序资源中添加并合并相应的资源字典。

猜你喜欢

转载自blog.csdn.net/qq_43511299/article/details/121631716