如何:定义和引用资源

此示例演示如何使用 Extensible Application Markup Language (XAML) 中的属性定义资源并引用它。

示例

以下示例定义两种类型的资源:一种 SolidColorBrush 资源和多个 Style 资源。 SolidColorBrush 资源 MyBrush 用于提供多个属性的值,每个属性都采用 Brush 类型的值。 Style 资源 PageBackgroundTitleTextLabel 每个都针对特定的控件类型。 当样式资源由资源键引用并用于设置 XAML 中定义的几个特定控件元素的 Style 属性时,样式会在目标控件上设置各种不同的属性。

请注意,Label 样式的资源库中的属性之一也引用了之前定义的 MyBrush 资源。 这是一种常见的技术,但重要的是要记住,资源是按照给定的顺序解析并输入到资源字典中的。 如果使用 StaticResource 标记扩展从其他资源中引用资源,则也会按照在字典中找到的顺序请求资源。 请确保引用的任何资源在资源集合中的定义早于随后请求该资源的位置。 如有必要,可通过使用 DynamicResource 标记扩展在运行时引用资源来解决资源引用的严格创建顺序,但你需要知道,这种 DynamicResource 技术会影响性能。 有关详细信息,请参阅 XAML 资源

<Page Name="root"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>
    <SolidColorBrush x:Key="MyBrush" Color="Gold"/>
    <Style TargetType="Border" x:Key="PageBackground">
      <Setter Property="Background" Value="Blue"/>
    </Style>
    <Style TargetType="TextBlock" x:Key="TitleText">
      <Setter Property="Background" Value="Blue"/>
      <Setter Property="DockPanel.Dock" Value="Top"/>
      <Setter Property="FontSize" Value="18"/>
      <Setter Property="Foreground" Value="#4E87D4"/>
      <Setter Property="FontFamily" Value="Trebuchet MS"/>
      <Setter Property="Margin" Value="0,40,10,10"/>
    </Style>
    <Style TargetType="TextBlock" x:Key="Label">
      <Setter Property="DockPanel.Dock" Value="Right"/>
      <Setter Property="FontSize" Value="8"/>
      <Setter Property="Foreground" Value="{StaticResource MyBrush}"/>
      <Setter Property="FontFamily" Value="Arial"/>
      <Setter Property="FontWeight" Value="Bold"/>
      <Setter Property="Margin" Value="0,3,10,0"/>
    </Style>
  </Page.Resources>
  <StackPanel>
    <Border Style="{StaticResource PageBackground}">
      <DockPanel>
        <TextBlock Style="{StaticResource TitleText}">Title</TextBlock>
        <TextBlock Style="{StaticResource Label}">Label</TextBlock>
        <TextBlock DockPanel.Dock="Top" HorizontalAlignment="Left" FontSize="36" Foreground="{StaticResource MyBrush}" Text="Text" Margin="20" />
        <Button DockPanel.Dock="Top" HorizontalAlignment="Left" Height="30" Background="{StaticResource MyBrush}" Margin="40">Button</Button>
        <Ellipse DockPanel.Dock="Top" HorizontalAlignment="Left" Width="100" Height="100" Fill="{StaticResource MyBrush}" Margin="40" />
      </DockPanel>
    </Border>
  </StackPanel>
</Page>

另请参阅