如何:使用应用程序资源

更新:2007 年 11 月

本示例演示如何使用应用程序资源。

示例

下面的示例演示应用程序定义文件。应用程序定义文件定义资源部分(Resources 属性的值)。构成应用程序的所有其他页可以访问在应用程序级别定义的资源。这种情况下,资源是声明样式。因为包含控件模板的完整样式可能很长,本示例删除了在样式的 ContentTemplate 属性 setter 中定义的控件模板。

<Application.Resources>
  <Style TargetType="Button" x:Key="GelButton" >
    <Setter Property="Margin" Value="1,2,1,2"/>
    <Setter Property="HorizontalAlignment" Value="Left"/>
    <Setter Property="Template">
      <Setter.Value>


...


      </Setter.Value>
    </Setter>
  </Style>
</Application.Resources>

下面的示例演示了引用上例中定义的应用程序级资源的 XAML 页。通过使用 StaticResource 标记扩展(用于指定请求的资源的唯一资源键)引用该资源。在当前页中没有找到具有“GelButton”键的资源,所以请求资源的资源查找范围超出当前页,进入已定义的应用程序级资源。

<StackPanel
  Name="root"
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  >
  <Button Height="50" Width="250" Style="{StaticResource GelButton}" Content="Button 1" />
  <Button Height="50" Width="250" Style="{StaticResource GelButton}" Content="Button 2" />
</StackPanel>

有关完整示例(包含完整控件模板),请参见应用程序资源示例

请参见

概念

资源概述

应用程序管理概述

其他资源

资源帮助主题

资源示例 (WPF)