練習:使用全應用程式範圍的資源

已完成

此練習的目的是透過將資源移動到 Tip Calculator 應用程式類別中的資源字典,使其可跨多個頁面使用。

此練習是前一個練習的延續。 您可以使用現有的解決方案做為這些步驟的起點,或開啟您在第一次練習中複製存放庫中 exercise4/TipCalculator 資料夾內的 TipCalculator 專案。

確認頁面層級資源

讓我們確認在一個頁面上定義的資源無法在另一個頁面上使用。 本節結束時,您的應用程式為正確執行。 不過,您會在下一節加以修正。

  1. 在 [TipCalculator] 專案中,開啟 CustomTipPage.xaml 檔案。

  2. 設定 infoLabelStyle 資源做為 billLabel 標籤的樣式,並移除 FontSizeFontAttributes 屬性的現有設定。

    <Label x:Name="billLabel" Text="Bill" Style="{StaticResource infoLabelStyle}" Grid.Row="0" Grid.Column="0" />
    
  3. 執行應用程式。

  4. 選取 [使用自訂計算機] 以顯示 [CustomTipPage] 頁面。 查看 [帳單] 標籤。 字型大小應該比其他標籤更小,且不是粗體。 會有此行為是因為頁面未找到名為 infoLabelStyle 的資源 (其位於不同頁面的資源字典中),因此字型大小和字型屬性會使用預設值。

    A screenshot of the CustomTipPage page. The Bill label isn't styled correctly.

為應用程式層級的資源建立字典

讓我們建立一個全應用程式範圍的字典,以保存要在多個頁面上使用的資源。

  1. 開啟 App.xaml 檔案。 請注意,此檔案目前包含一個資源字典,其中包含一些現有資源字典和樣式,預設會用於 .NET MAUI 內建的控制項。 要查看預設包含的所有樣式,請檢視 Resources/Styles.xaml 檔案。

    <?xml version = "1.0" encoding = "UTF-8" ?>
    <Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:TipCalculator"
                 x:Class="TipCalculator.App">
        <Application.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="Resources/Colors.xaml" />
                    <ResourceDictionary Source="Resources/Styles.xaml" />
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Application.Resources>
    </Application>
    
  2. 開啟 StandardTipPage.xaml 檔案,並將 fontSize 資源、baseLabelStyleinfoLabelStyle 樣式移動至 App.xaml 中的資源字典中。 將它們放在現有樣式之後,使 App.Xaml 檔案看起來像以下範例:

    <Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 ...>
        <Application.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="Resources/Colors.xaml" />
                    <ResourceDictionary Source="Resources/Styles.xaml" />
                </ResourceDictionary.MergedDictionaries>
    
                <Color x:Key="bgColor">#C0C0C0</Color>
                <Color x:Key="fgColor">#0000AD</Color>
                <x:Double x:Key="fontSize">22</x:Double>
    
                <Style x:Key="baseLabelStyle" TargetType="Label">
                    <Setter Property="FontSize" Value="{StaticResource fontSize}" />
                </Style>
                <Style x:Key="infoLabelStyle" BasedOn="{StaticResource baseLabelStyle}" TargetType="Label">
                    <Setter Property="FontAttributes" Value="Bold" />
                </Style>
            </ResourceDictionary>
        </Application.Resources>
    </Application>
    
  3. 執行應用程式。

  4. 選取 [使用自訂小算盤] 索引標籤,並確認現在 [帳單] 標籤的樣式設定正確。