Share via


HOW TO:使用應用程式範圍的資源字典

這個範例顯示如何定義和使用應用程式範圍的自訂資源字典。

範例

Application 會針對共用資源公開應用程式範圍的存放區:Resources。 根據預設,Resources 屬性是以 ResourceDictionary 型別的執行個體初始化。 當您使用 Resources 取得及設定應用程式範圍的屬性時,會使用這個執行個體 (如需詳細資訊,請參閱 HOW TO:取得和設定應用程式範圍的資源)。

如果要用 Resources 設定的資源不止一個,您可以改為使用自訂資源字典來存放這些資源,然後將 Resources 設為這個字典。 以下示範如何使用 XAML 宣告自訂資源字典。

<ResourceDictionary 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://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
Dim GradientBrush As Brush = Application.Current.FindResource("StandardLinearGradientBrush")
//Get a resource from the ResourceDictionary in code
Brush gradientBrush = (Brush)Application.Current.FindResource("StandardLinearGradientBrush");

使用 Resources 時需要進行兩項考量。 首先,字典 key 是一個物件,因此您在設定和取得屬性值時,必須使用完全相同的物件執行個體 (請注意,使用字串時,key 區分大小寫)。其次,字典 value 是一個物件,因此在取得屬性值時,必須將這個值轉換為所需的型別。

請參閱

參考

ResourceDictionary

Resources

概念

資源概觀

合併的資源字典