如何:使用应用程序资源

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

示例

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

<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="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://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>

另请参阅