如何:使用应用程序范围的资源字典
此示例演示如何定义和使用应用程序范围的自定义资源字典。
例
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
密钥,请在显式键属性之前声明它。 有关详细信息,请参阅 样式、DataTemplates 和隐式键。