作用:一個應用程序中,某個窗口需要使用樣式,但是樣式非常多,寫在一個窗口中代碼分類不方便。最好Style寫在專門的xaml文件中,然后引用到窗口中,就像HTML引用外部css文件一樣。
初衷:就在於可以實現多個項目之間的共享資源,資源字典只是一個簡單的XAML文檔,該文檔除了存儲希望使用的資源之外,不做任何其它的事情。
1. 創建資源字典
創建資源字典的過程比較簡單,只是將需要使用的資源全都包含在一個xaml文件之中即可。如下面的例子(文件名test.xaml,與后面的app.xaml文件中的內容相對應):
<?xml version="1.0" encoding="utf-8"?>
<!--This file is auto generated by XDraw.-->
<!--Do not modify this file directly, or your changes will be overwritten.-->
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<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. 使用字典中的資源