如何:使用應用程式範圍的資源字典
此範例示範如何定義和使用應用程式範圍自訂資源字典。
範例
Application 會公開共用資源的應用程式範圍存放區: Resources 。 根據預設, Resources 屬性會使用 型別的 ResourceDictionary 實例初始化。 當您使用 Resources 取得和設定應用程式範圍屬性時,請使用這個實例。 如需詳細資訊,請參閱 如何:取得和設定應用程式範圍資源 。
如果您有使用 Resources 設定的多個資源,您可以改用自訂資源字典來儲存這些資源,並改用它進行設定 Resources 。 下列示範如何使用 XAML 宣告自訂資源字典。
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<SolidColorBrush x:Key="StandardSolidColorBrush" Color="Blue" />
<LinearGradientBrush x:Key="StandardLinearGradientBrush" StartPoint="0.0,0.0" EndPoint="1.0,1.0">
<LinearGradientBrush.GradientStops>
<GradientStop Color="White" Offset="0" />
<GradientStop Color="Black" Offset="1" />
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</ResourceDictionary>
使用 Resources 交換整個資源字典可讓您支援應用程式範圍主題,其中每個主題都是由單一資源字典封裝。 下列範例會示範如何設定 ResourceDictionary。
<!--Set the Application ResourceDictionary-->
<Application.Resources>
<ResourceDictionary Source="MyResourceDictionary.xaml" />
</Application.Resources>
下列示範如何從 XAML 中 Resources 公開的資源字典取得應用程式範圍資源。
<!--Set the brush as a StaticResource from the ResourceDictionary-->
<Rectangle Name="Rect" Height="200" Width="100" Fill="{StaticResource ResourceKey=StandardSolidColorBrush}" />
下列會顯示也可以如何使用程式碼來取得資源。
//Get a resource from the ResourceDictionary in code
Brush gradientBrush = (Brush)Application.Current.FindResource("StandardLinearGradientBrush");
'Get a resource from the ResourceDictionary in code
Dim GradientBrush As Brush = Application.Current.FindResource("StandardLinearGradientBrush")
使用 Resources 時,有兩個考慮。 首先,字典「索引鍵」是一個物件,因此,您在設定和取得屬性值時必須使用完全相同的物件執行個體 (請注意,使用字串時,索引鍵會區分大小寫。其次,字典 值 是 物件,因此您必須在取得屬性值時,將值轉換成所需的型別。
某些資源類型可能會自動使用型別所定義的屬性做為明確的索引鍵,例如 Style 和 DataTemplate 型別。 這可能會覆寫您的 x:Key
值。 若要保證遵守您的 x:Key
金鑰,請在明確索引鍵屬性之前宣告它。 如需詳細資訊,請參閱 Styles、DataTemplates 和隱含索引鍵 。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應