如何:使用应用程序范围的资源字典
此示例演示如何定义和使用应用程序范围的自定义资源字典。
示例
Application 为共享的资源 Resources 公开应用程序范围的存储区。 默认情况下,使用 ResourceDictionary 类型的实例初始化 Resources 属性。 当您使用 Resources 获取并设置应用程序范围的属性时,可以使用此实例。 (有关更多信息,请参见如何:获取和设置应用程序范围的资源。)
如果您有多个使用 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 时有两个注意事项。 首先,字典的键 是一个对象,因此设置和获取属性值时必须使用完全相同的对象实例。 (请注意:使用字符串时该键区分大小写。)其次,字典的值 是一个对象,因此获取属性值时需要将该值转换成需要的类型。