Share via


取用 XAML 標記延伸

Browse sample. 流覽範例

.NET 多平臺應用程式 UI (.NET MAUI) XAML 標記延伸可藉由允許從各種來源設定元素屬性,協助增強 XAML 的功能和彈性。

例如,您通常會設定 Color 如下的 BoxView 屬性:

<BoxView Color="Blue" />

不過,建議您改為 Color 從儲存在資源字典中的值,或從您所建立類別的靜態屬性值,或從頁面上另一個元素類型的 Color 屬性,或從個別色調、飽和度和亮度值建構的屬性設定屬性。 所有這些選項都可以使用 XAML 標記延伸。

標記延伸是表示項目屬性的不同方式。 .NET MAUI XAML 標記延伸通常是由大括弧括住的屬性值來識別:

<BoxView Color="{StaticResource themeColor}" />

大括弧中的任何屬性值一律XAML 標記延伸。 不過,XAML 標記延伸也可以在不使用大括弧的情況下參考。

注意

數個 XAML 標記延伸是 XAML 2009 規格的一部分。 這些檔案會出現在具有自定義 x 命名空間前置詞的 XAML 檔案中,而且通常會使用此前置詞來參考。

除了本文所討論的標記延伸之外,.NET MAUI 中還包含下列標記延伸,並在其他文章中討論:

x:Static 標記延伸

類別 x:Static 支持 StaticExtension 標記延伸。 類別具有名為 Member 之類型的 string 單一屬性,您設定為公用常數、靜態屬性、靜態欄位或列舉成員的名稱。

使用 x:Static 的方法之一是先定義具有某些常數或靜態變數的類別,例如這個 AppConstants 類別:

static class AppConstants
{
    public static double NormalFontSize = 18;
}

下列 XAML 示範在屬性元素標記之間Label.FontSize具現StaticExtension化類別的最詳細資訊方法:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:sys="clr-namespace:System;assembly=netstandard"
             xmlns:local="clr-namespace:MarkupExtensions"
             x:Class="MarkupExtensions.StaticDemoPage"
             Title="x:Static Demo">
    <StackLayout Margin="10, 0">
        <Label Text="Label No. 1">
            <Label.FontSize>
                <x:StaticExtension Member="local:AppConstants.NormalFontSize" />
            </Label.FontSize>
        </Label>
        ···
    </StackLayout>
</ContentPage>

XAML 剖析器也允許 StaticExtension 將 類別縮寫為 x:Static

<Label Text="Label No. 2">
    <Label.FontSize>
        <x:Static Member="local:AppConstants.NormalFontSize" />
    </Label.FontSize>
</Label>

藉由將 類別和成員設定放在 StaticExtension 大括弧中,即可進一步簡化此語法。 產生的運算式會直接設定為 FontSize 屬性:

<Label Text="Label No. 3"
       FontSize="{x:StaticExtension Member=local:AppConstants.NormalFontSize}" />

在此範例中, 大括弧內沒有 引號。 的 MemberStaticExtension 屬性不再是 XML 屬性。 它不是標記延伸的表達式的一部分。

就像當您使用它做為物件元素時可以縮寫x:StaticExtensionx:Static一樣,您也可以在大括弧內的表達式中縮寫它:

<Label Text="Label No. 4"
       FontSize="{x:Static Member=local:AppConstants.NormalFontSize}" />

類別 StaticExtension 具有 ContentProperty 參考 屬性的屬性 Member,此屬性會將此屬性標示為類別的預設內容屬性。 針對以大括弧表示的 XAML 標記延伸,您可以排除 Member= 表達式的一部分:

<Label Text="Label No. 5"
       FontSize="{x:Static local:AppConstants.NormalFontSize}" />

這是標記延伸最常見的形式 x:Static

XAML 範例的根標記也包含 .NET System 命名空間的 XML 命名空間宣告。 這可讓 Label 字型大小設定為靜態欄位 Math.PI。 這會產生相當小的文字,因此 Scale 屬性會設定為 Math.E

<Label Text="&#x03C0; &#x00D7; E sized text"
       FontSize="{x:Static sys:Math.PI}"
       Scale="{x:Static sys:Math.E}"
       HorizontalOptions="Center" />

下列螢幕快照顯示 XAML 輸出:

x:Static demo.

x:Reference markup extension

類別 x:Reference 支持 ReferenceExtension 標記延伸。 類別具有名為 Name 之類型的 string 單一屬性,您設定為頁面上已指定名稱的項目名稱 x:Name。 這個 Name 屬性是 的內容屬性 ReferenceExtension,因此 Name= 在大括弧中出現時 x:Reference 不需要。 標記 x:Reference 延伸僅與數據系結搭配使用。 如需數據系結的詳細資訊,請參閱 數據系結

下列 XAML 範例示範兩個 搭配數據系結的 用法 x:Reference ,第一個是用來設定 Source 對象的 屬性 Binding ,第二個是用來設定 BindingContext 兩個數據系結的 屬性:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MarkupExtensions.ReferenceDemoPage"
             x:Name="page"
             Title="x:Reference Demo">    
    <StackLayout Margin="10, 0">        
        <Label Text="{Binding Source={x:Reference page},
                              StringFormat='The type of this page is {0}'}"
               FontSize="18"
               VerticalOptions="Center"
               HorizontalTextAlignment="Center" />
        <Slider x:Name="slider"
                Maximum="360"
                VerticalOptions="Center" />
        <Label BindingContext="{x:Reference slider}"
               Text="{Binding Value, StringFormat='{0:F0}&#x00B0; rotation'}"
               Rotation="{Binding Value}"
               FontSize="24"
               HorizontalOptions="Center"
               VerticalOptions="Center" />        
    </StackLayout>
</ContentPage>

在此範例中,這兩個表達式都會 x:Reference 使用類別名稱的 ReferenceExtension 縮寫版本,並消除 Name= 表達式的一部分。 在第一個範例中, x:Reference 標記延伸會內嵌在標記延伸中 Binding ,而 SourceStringFormat 屬性則以逗號分隔。

下列螢幕快照顯示 XAML 輸出:

x:Reference demo.

x:Type 標記延伸

標記 x:Type 延伸是 C# typeof 關鍵詞的 XAML 對等專案。 類別支援 TypeExtension 此類別,其定義 TypeName 應該設定為類別或結構名稱之型 string 別的屬性。 標記延伸會x:TypeType傳回該類別或結構的物件。 TypeName 是的內容屬性 TypeExtension,因此 TypeName= 在以大括弧出現時 x:Type 不需要。

標記 x:Type 延伸通常與標記延伸搭配 x:Array 使用。 如需詳細資訊,請參閱 x:Array 標記延伸

下列 XAML 範例示範如何使用 x:Type 標記延伸來具現化 .NET MAUI 物件,並將其新增至 StackLayout。 XAML 包含三 Button 個元素,其 Command 屬性設定為 , BindingCommandParameter 屬性設定為三種 .NET MAUI 檢視的類型:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MarkupExtensions.TypeDemoPage"
             Title="x:Type Demo">    
    <StackLayout x:Name="stackLayout"
                 Padding="10, 0">        
        <Button Text="Create a Slider"
                HorizontalOptions="Center"
                VerticalOptions="Center"
                Command="{Binding CreateCommand}"
                CommandParameter="{x:Type Slider}" />
        <Button Text="Create a Stepper"
                HorizontalOptions="Center"
                VerticalOptions="Center"
                Command="{Binding CreateCommand}"
                CommandParameter="{x:Type Stepper}" />
        <Button Text="Create a Switch"
                HorizontalOptions="Center"
                VerticalOptions="Center"
                Command="{Binding CreateCommand}"
                CommandParameter="{x:Type Switch}" />
    </StackLayout>
</ContentPage>

程式代碼後置檔案會定義並初始化 CreateCommand 屬性:

public partial class TypeDemoPage : ContentPage
{
    public ICommand CreateCommand { get; private set; }

    public TypeDemoPage()
    {
        InitializeComponent();

        CreateCommand = new Command<Type>((Type viewType) =>
        {
            View view = (View)Activator.CreateInstance(viewType);
            view.VerticalOptions = LayoutOptions.Center;
            stackLayout.Add(view);
        });

        BindingContext = this;
    }
}

Button按下 時,會建立 自變數的新實例CommandParameter,並將其新增至 StackLayout。 然後,這三 Button 個物件會與動態建立的檢視共享頁面:

x:Type demo.

x:Array 標記延伸

標記 x:Array 延伸可讓您在標記中定義陣列。 類別支援 ArrayExtension 此類別,其定義兩個屬性:

  • TypeType別 為 ,表示陣列中專案的型別。 此屬性應該設定為 x:Type 標記延伸。
  • ItemsIList別 為 ,這是專案本身的集合。 這是的內容 ArrayExtension屬性。

標記 x:Array 延伸本身永遠不會以大括號顯示。 相反地, x:Array 開始和結束標記會分隔項目清單。

下列 XAML 範例示範如何使用 x:Array 將 屬性設定ItemsSource為陣列,將專案新增至 ListView

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MarkupExtensions.ArrayDemoPage"
             Title="x:Array Demo Page">
    <ListView Margin="10">
        <ListView.ItemsSource>
            <x:Array Type="{x:Type Color}">
                <Color>Aqua</Color>
                <Color>Black</Color>
                <Color>Blue</Color>
                <Color>Fuchsia</Color>
                <Color>Gray</Color>
                <Color>Green</Color>
                <Color>Lime</Color>
                <Color>Maroon</Color>
                <Color>Navy</Color>
                <Color>Olive</Color>
                <Color>Pink</Color>
                <Color>Purple</Color>
                <Color>Red</Color>
                <Color>Silver</Color>
                <Color>Teal</Color>
                <Color>White</Color>
                <Color>Yellow</Color>
            </x:Array>
        </ListView.ItemsSource>
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <BoxView Color="{Binding}"
                             Margin="3" />
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>     

在此範例中, ViewCell 會為每個色彩專案建立一 BoxView 個簡單的專案:

x:Array demo.

注意

定義字串或數位等常見類型的數位時,請使用Pass自變數中列出的 XAML 語言基本標記。

x:Null 標記延伸

類別 x:Null 支持 NullExtension 標記延伸。 它沒有屬性,只是 C# null 關鍵詞的 XAML 對等專案。

下列 XAML 範例示範如何使用 x:Null 標記延伸:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MarkupExtensions.NullDemoPage"
             Title="x:Null Demo">
    <ContentPage.Resources>
        <Style TargetType="Label">
            <Setter Property="FontSize" Value="48" />
            <Setter Property="FontFamily" Value="OpenSansRegular" />
        </Style>
    </ContentPage.Resources>

    <StackLayout Padding="10, 0">
        <Label Text="Text 1" />
        <Label Text="Text 2" />
        <Label Text="Text 3"
               FontFamily="{x:Null}" />
        <Label Text="Text 4" />
        <Label Text="Text 5" />
    </StackLayout>
</ContentPage>      

在這裡範例中,會針對 Label 定義隱含Style的 ,其中包含 Setter 將屬性設定FontFamily為特定字型的 。 不過,第三 Label 個會藉由將 字 FontFamily 型設定為 x:Null來避免使用隱含樣式中定義的字型:

x:Null demo.

DataTemplate 標記延伸

標記 DataTemplate 延伸可讓您將型別轉換成 DataTemplate。 類別支援 DataTemplateExtension 此類別,其定義 TypeNamestring別 的屬性,其設定為要轉換成 DataTemplate之型別的名稱。 屬性 TypeName 是的內容 DataTemplateExtension屬性。 因此,對於以大括弧表示的 XAML 標記表示式,您可以排除 TypeName= 表達式的一部分。

注意

XAML 剖析器允許將 DataTemplateExtension 類別縮寫為 DataTemplate

此標記延伸的一般用法是在Shell應用程式中,如下列範例所示:

<ShellContent Title="Monkeys"
              Icon="monkey.png"
              ContentTemplate="{DataTemplate views:MonkeysPage}" />

在此範例中, MonkeysPage 會從 ContentPageDataTemplate轉換成 ,其設定為 屬性的值 ShellContent.ContentTemplate 。 這可確保 MonkeysPage 只有在瀏覽至頁面時才會建立,而不是在應用程式啟動時建立。

如需殼層應用程式的詳細資訊,請參閱 Shell