做用:一个应用程序中,某个窗口须要使用样式,可是样式很是多,写在一个窗口中代码分类不方便。最好Style写在专门的xaml文件中,而后引用到窗口中,就像HTML引用外部css文件同样。css
初衷:就在于能够实现多个项目之间的共享资源,资源字典只是一个简单的XAML文档,该文档除了存储但愿使用的资源以外,不作任何其它的事情。app
1. 建立资源字典布局
建立资源字典的过程比较简单,只是将须要使用的资源全都包含在一个xaml文件之中便可。以下面的例子(文件名test.xaml,与后面的app.xaml文件中的内容相对应):this
<?xml version="1.0" encoding="utf-8"?>编码
<!--This file is auto generated by XDraw.-->spa
<!--Do not modify this file directly, or your changes will be overwritten.-->xml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">utf-8
<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文件中进行集成。代码以下:
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Test.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
2.2 使用资源
集成以后就能够在当前的工程中使用这些资源了。使用方法以下:
<Window x:Class="HelloWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="340" Width="406" WindowStartupLocation="CenterScreen"
Icon="SC.ico" >
<Grid Height="304" Width="374">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Margin="121,30,107,230" Grid.Row="2" Click="Button_Click" Background="{StaticResource FadeBrush}">
</Button>
</Grid>
</Window>
使用资源的方法比较简单只须要使用StaticResource 关键字去添加便可。
2.1内部集成
或者内部集成在窗口中引用外部资源,注意:在Window中添加外部样式须要指定key,而Application中则不须要,因此这里FadeBrush就是引用外部样式test.xaml的key
<Window x:Class="MSSQLDocCreator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MSSQLDocCreator"
Title="MainWindow" Height="602" Width="425" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ResourceDictionary x:Key="FadeBrush">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="test.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
....
</Window>
将样式应用到窗口的布局上
<Grid Resources="{StaticResource rdStyle}">
</Grid>
3. 总结:
使用资源字典的主要缘由有两个:
a. 提供皮肤功能。
b. 存储须要被本地话的内容(错误消息字符串等,实现软编码)
使用过程也比较简单,概括起来主要有下面几个步骤:
1. 建立资源字典文件
2. 资源字典集成
3. 使用字典中的资源