共用方式為


HOW TO:使用應用程式資源

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

範例

下列範例顯示應用程式定義檔案。 應用程式定義檔案定義了資源區段 (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>

請參閱

概念

資源概觀

應用程式管理概觀

其他資源

資源 HOW TO 主題