一、WPF支持程式級資源(也稱為二進制資源),和物件級資源,

二、物件級資源簡介
- 簡介:物件級資源主要是被應用到各個界面元素中,而每個WPF界面元素都具有一個Resource屬性,這個屬性繼承自FrameworkElement類,其型別為ResourceDictionary(ResourceDictionary是以"鍵-值"的形式存盤資源,通過索引找到資源并應用),
- 物件級資源的應用場景主要分為三個:
① Application的物件級資源:每新建一個WPF應用,就會自動生成一個App.xaml,這個檔案最常用的特性是定義全域資源,這些資源會在整個應用里面被使用,
1 <Application> 2 <Application.Resources> 3 <TextBlock x:Key="Res1" Text="Hello"/> 4 </Application.Resources> 5 </Application>
② 界面元素的物件級資源:可放在任一控制元件的Resource屬性中,但通常將其放在界面的根元素上,起生效范圍是當前界面,
1 <Window> 2 < Window.Resources> 3 <TextBlock x:Key="Res1" Text="Hello"/> 4 </ Window.Resources> 5 </Window>
③ 將物件級資源封裝成外部資源字典:將物件級資源統一放在資源字典中,在需要使用的地方將其集成,一般都在App.xaml中對資源進行集成,
1 <UserControl> 2 <UserControl.Resources> 3 <ResourceDictionary Source="Res/ControlForDemo.xaml"/> 4 </UserControl.Resources> 5 </UserControl>
而資源字典的內容如下:
1 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 2 xmlns:local="clr-namespace:DependencyPropertyDemo.Res"> 3 <TextBlock x:Key="Res1" Text="Fighting" x:Shared ="False"/> 4 </ResourceDictionary>
- x:Shared = "true":對每次請求的資源都使用同個實體,
- x:Shared = "false":對每次請求的資源都創建一個新的實體,詳細決議:WPF學習之四:x:Shared概述 - 潮兒 - 博客園 (cnblogs.com)
- 資源字典的編譯選項:page或者Resource,
—— page:可以保證XAML資源檔案最終被編譯為baml檔案,然后可以作為資源插入到.NET框架中,在運行時,框架引擎提取并決議.baml,然后創建一個相應的WPF視覺樹或作業流,
—— Resource:可以嵌入到程式集中,但是不被編譯,其決議速度會稍微慢一點,
三、資源字典的集成
- XAML集成外部資源字典
1 <UserControl> 2 <UserControl.Resources> 3 <ResourceDictionary> 4 <ResourceDictionary.MergedDictionaries> 5 <ResourceDictionary Source="Res/ButtonStyle.xaml"/> 6 <ResourceDictionary Source="Res/TextBoxStyle.xaml"/> 7 </ResourceDictionary.MergedDictionaries> 8 </ ResourceDictionary> 9 </UserControl.Resources> 10 </UserControl>
ResourceDictionary.MergedDictionaries:該屬性是一個ResourceDictionary物件的集合,可以使用這個集合提供多個資源檔案,注意:MergedDictionaries下面的每一個ResourceDictionary都必須是獨立的,多個ResourceDictionary之間不可以相互參考;ResourceDictionary中定義的key是先進后出的,所以獲取到的順序和定義的順序是相反的,
- C#后臺代碼集成外部資源字典
this.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new System.Uri("pack://application:,,,/AddResourceFile;component/Res/TextBoxStyle.xaml") });
四、物件級資源的使用
- 在XAML中使用資源
1 <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> 2 <Label Content="{StaticResource Res1}" HorizontalAlignment="Center"/> 3 <Label Content="{DynamicResource Res2}" HorizontalAlignment="Center"/> 4 </StackPanel>
① StaticResource:僅在程式載入記憶體時訪問該資源一次;
② DynamicResource:程式在運行程序中每次使用都會重新訪問該資源;
- 在C#后臺代碼中使用資源
1 private void Button_Click(object sender, RoutedEventArgs e) 2 { 3 this.label1.Content = this.Resources["Res1"]; 4 this.label2.Content = this.FindResource("Res2"); 5 }
① FindResource:如果找不到請求的資源,會引發例外;
② Resources:獲取本地的資源,找不到沒有例外;
五、物件級資源的檢索方式
- 首先是查找控制元件自己的Resource屬性,若查不到,會沿著邏輯樹一級級的查找父控制元件的Resource屬性;
- 若在父級控制元件中都查不到,就會去查找Application的Resource屬性;
- 若仍然查找不到,則會例外處理,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/378075.html
標籤:WPF
