Share via


如何:使用應用程式資源

這個範例示範如何使用應用程式資源。

範例

下列範例顯示應用程式定義檔案。 應用程式定義檔會定義資源區段(屬性的值 Resources )。 如果資源是定義為應用程式層級,則應用程式當中的其他所有頁面均可存取這些資源。 在此情況下,這類資源是宣告的樣式。 由於包含控制項範本的完整樣式可能很冗長,此範例會省略樣式屬性 setter 內 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>

另請參閱