第10章 资源(2)——资源字典

来源:互联网 发布:sql sever设置主键 编辑:程序博客网 时间:2024/05/16 17:46

一、概述

当在一个Resources集合中定义较复杂的资源时或一个Resources集合的资源太多不便于管理或需要在多个项目间共享资源时,可通过资源字典方便的解决上述问题。资源字典只是XAML文档,除了存储希望使用的资源外,不做其他任何事情。

二、创建资源字典

①在项目上[右击]选择[添加]找到[资源字典]

②当为应用程序添加资源字典时,务必在其属性页中将[生成操作]改为Page。这样可保证为了获得最佳性能而将资源字典编译为BAML。不过,将资源字典的[生成操作]改为Resource也非常完美,这样它会被嵌入导程序集中,但不会被编译。当然,在运行时解析它的速度要稍慢一些。

三、使用资源字典

为了使用资源字典,需要将其合并到应用程序某些位置的资源集合中,通常将其合并到应用程序的资源集合中。

<Application x:Class="ResourcesDemo.App"             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"             xmlns:local="clr-namespace:ResourcesDemo"             StartupUri="MainWindow.xaml">    <Application.Resources>        <ResourceDictionary>            <ResourceDictionary.MergedDictionaries>                <ResourceDictionary Source="MyImageBrush.xaml"/>            </ResourceDictionary.MergedDictionaries>        </ResourceDictionary>    </Application.Resources></Application>
如果希望添加字节的资源并合并到资源字典中,只需要在MergedDictionaries部分之前或之后放置资源就可以了。
<Application x:Class="ResourcesDemo.App"             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"             xmlns:local="clr-namespace:ResourcesDemo"             StartupUri="MainWindow.xaml">    <Application.Resources>        <ResourceDictionary>            <ResourceDictionary.MergedDictionaries>                <ResourceDictionary Source="MyImageBrush.xaml"/>            </ResourceDictionary.MergedDictionaries>            <ImageBrush x:Key="AnotherBrush" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 32 32"                    ImageSource="/Images/cry.png" Opacity="0.3">            </ImageBrush>        </ResourceDictionary>    </Application.Resources></Application>


0 0
原创粉丝点击