WPF资源字典使用

资源字典出现的初衷就在于可以实现多个项目之间的共享资源,资源字典只是一个简单的XAML文档,该文档除了存储希望使用的资源之外,不做任何其它的事情。

 

1.  创建资源字典

      创建资源字典的过程比较简单,只是将需要使用的资源全都包含在一个xaml文件之中即可。如下面的例子(文件名xxx.xaml,与后面的app.xaml文件中的内容相对应):

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!--自定义按钮样式-->
    <Style x:Key="myBtnStyleOne" TargetType="Button">
        <Setter Property="FontFamily" Value="Arial"></Setter>
        <Setter Property="Padding" Value="10"></Setter>
        <Setter Property="Width" Value="100"></Setter>
        <Setter Property="Height" Value="40"></Setter>
    </Style>
    <!--自定义渐变画笔-->
    <LinearGradientBrush x:Key="fadeBrush">
        <GradientStop Color="Red" Offset="0"/>
        <GradientStop Color="Gray" Offset="1"/>
    </LinearGradientBrush>
</ResourceDictionary>

 说明:在创建资源的时候要确保资源文件的编译选项为page,这样就能够保证XAML资源文件最终能够编译为baml文件。但是如果设置为Resource也是一个不错的选择,这样它能够嵌入到程序集中,但是不被编译,当然其解析的速度回稍微慢一点。

2.  使用资源字典

2.1  集成资源

     要是用资源字典,首先要将资源字典集成到应用程序的某些资源集合中。一般的做法都是在app.xaml文件中进行集成。代码如下:

<Application x:Class="DataGridSolution.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    
    <Application.Resources>
        
        <!--集成资源-->
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resource/MyButtonStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
        
    </Application.Resources>
</Application>

 说明:上面的标记通过明确地创建一个ResourceDictionary对象进行工作,资源集合总是ResourceDictionary对象。但是这只是需要明确指定细节从而可以设定ResourceDictionary.MergedDictionaries属性的一种情况。如果没有这个步骤ResourceDictionary.MergedDictionaries属性将为空。ResourceDictionary.MergedDictionaries属性是一个ResourceDictionary对象的集合,可以使用这个集合提供自己需要使用的资源的集合。也就是说如果需要某个资源,只需要将与该资源相关的xaml文件。添加到这个属性中即可。如上面添加test.xaml一样。

2.2  使用资源

     集成之后就可以在当前的工程中使用这些资源了。使用方法如下:

        <Button Content="获取绑定数据"
                Style="{StaticResource ResourceKey=myBtnStyleOne}"
                Background="{StaticResource ResourceKey=fadeBrush}"
                HorizontalAlignment="Left" 
                Margin="283,49,0,0" VerticalAlignment="Top" 
               />

 使用资源的方法比较简单只需要使用StaticResource 关键字去添加即可。

 

3.  总结:

     使用资源字典的主要原因有两个:

    a. 提供皮肤功能。

    b. 存储需要被本地话的内容(错误消息字符串等,实现软编码)

     使用过程也比较简单,归纳起来主要有下面几个步骤:

    1. 创建资源字典文件  》 2. 资源字典集成 》  3. 使用字典中的资源

原文地址:https://www.cnblogs.com/tianma3798/p/3721389.html