使用級聯樣式表設計應用程式

.NET 多平臺應用程式 UI (.NET MAUI) 應用程式可以使用級聯樣式表 (CSS) 來設定樣式。 樣式表單包含規則清單,每個規則都包含一或多個選取器和宣告區塊。 宣告區塊是由大括弧中的宣告清單所組成,每個宣告都包含屬性、冒號和值。 當區塊中有多個宣告時,分號會插入為分隔符。

下列範例顯示一些符合 .NET MAUI 規範的 CSS:

navigationpage {
    -maui-bar-background-color: lightgray;
}

^contentpage {
    background-color: lightgray;
}

#listView {
    background-color: lightgray;
}

stacklayout {
    margin: 20;
    -maui-spacing: 6;
}

grid {
    row-gap: 6;
    column-gap: 6;
}
.mainPageTitle {
    font-style: bold;
    font-size: 14;
}

.mainPageSubtitle {
    margin-top: 15;
}

.detailPageTitle {
    font-style: bold;
    font-size: 14;
    text-align: center;
}

.detailPageSubtitle {
    text-align: center;
    font-style: italic;
}

listview image {
    height: 60;
    width: 60;
}

stacklayout>image {
    height: 200;
    width: 200;
}

在 .NET MAUI 中,CSS 樣式表單會在運行時間剖析和評估,而不是編譯時間,而且樣式表單會在使用時重新剖析。

重要

您無法使用 CSS 完整設定 .NET MAUI 應用程式的樣式。 不過,XAML 樣式可用來補充 CSS。 如需有關 XAML 樣式的詳細資訊,請參閱 使用 XAML 樣式應用程式

取用樣式表單

將樣式表單新增至 .NET MAUI 應用程式的程式如下:

  1. 將空白 CSS 檔案新增至 .NET MAUI 應用程式專案。 CSS 檔案可以放在任何資料夾中,Resources 資料夾是建議的位置。
  2. 將 CSS 檔案的建置動作設定為 MauiCss

載入樣式表單

有許多方法可用來載入樣式表單。

注意

您無法在運行時間變更樣式表單,並套用新的樣式表單。

在 XAML 中載入樣式表單

在加入至 StyleSheet之前,可以利用 ResourceDictionary 類別載入並解析樣式表單。

<Application ...>
    <Application.Resources>
        <StyleSheet Source="/Resources/styles.css" />
    </Application.Resources>
</Application>

StyleSheet.Source 屬性會將樣式表單指定為相對於封入 XAML 檔案位置的 URI,或如果 URI 以 /開頭,則指定相對於專案根目錄的 URI。

警告

如果 CSS 檔案的建置動作未設定為 MauiCss,將無法載入。

或者,您可以先使用 StyleSheet 類別載入並剖析樣式表,然後將其內嵌至 ResourceDictionary 區段中,添加至 CDATA

<ContentPage ...>
    <ContentPage.Resources>
        <StyleSheet>
            <![CDATA[
            ^contentpage {
                background-color: lightgray;
            }
            ]]>
        </StyleSheet>
    </ContentPage.Resources>
    ...
</ContentPage>

如需資源字典的詳細資訊,請參閱 資源字典

在 C 中載入樣式表單#

在 C# 中,樣式表單可以從 StringReader 載入,並新增至 ResourceDictionary

using Microsoft.Maui.Controls.StyleSheets;

public partial class MyPage : ContentPage
{
    public MyPage()
    {
        InitializeComponent();

        using (var reader = new StringReader("^contentpage { background-color: lightgray; }"))
        {
            this.Resources.Add(StyleSheet.FromReader(reader));
        }
    }
}

StyleSheet.FromReader 方法的自變數是已讀取樣式表單的 TextReader

選取元素並套用屬性

CSS 會使用選取器來判斷要設為目標的元素。 具有相符選取器的樣式會依定義順序連續套用。 特定項目上定義的樣式一律會套用到最後。 如需有關支援選取器的詳細資訊,請參閱選取器參考

CSS 會使用屬性來設定選取元素的樣式。 每個屬性都有一組可能的值,有些屬性可能會影響任何類型的專案,而其他屬性則套用至元素群組。 如需支援屬性的詳細資訊,請參閱 屬性參考

如果子樣式表單設定相同的屬性,子樣式表單一律會覆寫父樣式表單。 因此,套用設定相同屬性的樣式時,會遵循下列優先順序規則:

  • 如果設定相同的屬性,應用程式資源中定義的樣式將會由頁面資源中定義的樣式覆寫。
  • 如果頁面資源中定義的樣式與控件資源中定義的樣式設定相同的屬性,前者的樣式將會被後者覆蓋。
  • 如果控件資源中定義的樣式設置了相同的屬性,那麼應用程式資源中定義的樣式將會被覆寫。

注意

不支援 CSS 變數。

依類型選取元素

視覺樹中的元素可以使用不區分大小寫的 element 選擇器依類型來選取:

stacklayout {
    margin: 20;
}

此選取器會識別使用樣式表單之頁面上的任何 StackLayout 元素,並將其邊界設定為 20 的統一粗細。

注意

element 選取器不會識別指定類型的子類別。

依基類選取元素

在視覺樹狀結構中,元素可以通過基礎類別進行選取,並且可以使用不區分大小寫的 ^base 選取器。

^contentpage {
    background-color: lightgray;
}

這個選取器會辨識使用樣式表的任何 ContentPage 元素,並將其背景色彩設定為 lightgray

注意

^base 選取器是 .NET MAUI 特有的,而且不屬於 CSS 規格的一部分。

依名稱選取元素

您可以使用區分大小寫 #id 選取器選取視覺化樹狀結構中的個別元素:

#listView {
    background-color: lightgray;
}

這個選取器會識別出 StyleId 屬性被設定為 listView的元素。 不過,如果未設定 StyleId 屬性,選取器會退回到使用元素的 x:Name。 因此,在下列範例中,#listView 選取器會識別 ListView 屬性設定為 x:NamelistView,並將背景色彩設定為 lightgray

<ContentPage ...>
    <ContentPage.Resources>
        <StyleSheet Source="/Resources/styles.css" />
    </ContentPage.Resources>
    <StackLayout>
        <ListView x:Name="listView">
            ...
        </ListView>
    </StackLayout>
</ContentPage>

選取具有特定類別屬性的元素

您可以使用區分大小寫的 .class 選取器來選擇具有特定類別屬性的元素。

.detailPageTitle {
    font-style: bold;
    font-size: 14;
    text-align: center;
}

.detailPageSubtitle {
    text-align: center;
    font-style: italic;
}

您可以將元素的 StyleClass 屬性設定為 CSS 類別名稱,將 CSS 類別指派給 XAML 元素。 因此,在下列範例中,.detailPageTitle 類別定義的樣式會指派給第一個 Label,而 .detailPageSubtitle 類別定義的樣式則會指派給第二個 Label

<ContentPage ...>
    <ContentPage.Resources>
        <StyleSheet Source="/Resources/styles.css" />
    </ContentPage.Resources>
    <ScrollView>
        <StackLayout>
            <Label ... StyleClass="detailPageTitle" />
            <Label ... StyleClass="detailPageSubtitle"/>
        </StackLayout>
    </ScrollView>
</ContentPage>

選取子元素

您可以使用不區分大小寫 element element 選取器選取視覺化樹狀結構中的子元素:

listview image {
    height: 60;
    width: 60;
}

此選取器會識別 Image 專案子系的任何 ListView 專案,並將其高度和寬度設定為 60。 因此,在下列 XAML 範例中,listview image 選取器會識別 Image子系的 ListView,並將其高度和寬度設定為 60。

<ContentPage ...>
    <ContentPage.Resources>
        <StyleSheet Source="/Resources/styles.css" />
    </ContentPage.Resources>
    <StackLayout>
        <ListView ...>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid>
                            ...
                            <Image ... />
                            ...
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

注意

element element 選取器不需要子元素是父元素 的直接 子元素–子元素可以屬於不同的父元素。 當某一個祖先是指定的第一個元素時,就會發生選取。

選取直接子元素

您可以使用不區分大小寫 element>element 選取器選取視覺化樹狀結構中的直接子元素:

stacklayout>image {
    height: 200;
    width: 200;
}

此選取器會識別任何 Image 元素,這些元素是 StackLayout 元素的直接子系,並將其高度和寬度設定為 200 像素。 因此,在下列範例中,stacklayout>image 選取器會識別 Image的直接子系 StackLayout,並將其高度和寬度設定為 200。

<ContentPage ...>
    <ContentPage.Resources>
        <StyleSheet Source="/Resources/styles.css" />
    </ContentPage.Resources>
    <ScrollView>
        <StackLayout>
            ...
            <Image ... />
            ...
        </StackLayout>
    </ScrollView>
</ContentPage>

注意

element>element 選取器要求子元素是父系 的直接 子元素。

選取器參考

.NET MAUI 支援下列 CSS 選取器:

選擇器 描述
.class .header 選取包含 『header』 之 StyleClass 屬性的所有元素。 此選取器區分大小寫。
#id #email 選取所有 StyleId 設為 email的元素。 如果未設定 StyleId,則備用為 x:Name。 使用 XAML 時,x:Name 優先於 StyleId。 此選取器區分大小寫。
* * 選取所有元素。
element label 選取所有類型為 Label的元素,但不包括子類別。 此選取器不區分大小寫。
^base ^contentpage 選取具有 ContentPage 作為基類的所有元素,包括 ContentPage 本身。 此選取器不區分大小寫,且不屬於 CSS 規格的一部分。
element,element label,button 選取所有 Button 元素和所有 Label 元素。 此選取器不區分大小寫。
element element stacklayout label 選取 Label中的所有 StackLayout 元素。 此選取器不區分大小寫。
element>element stacklayout>label 選取 Label 作為直接父項的所有 StackLayout 元素。 此選取器不區分大小寫。
element+element label+entry 選取直接在 Entry之後的所有 Label 元素。 此選取器不區分大小寫。
element~element label~entry 選取所有前面由 Entry的元素所引導的 Label 元素。 此選取器不區分大小寫。

具有相符選取器的樣式會依定義順序連續套用。 特定項目上定義的樣式一律會套用到最後。

提示

選擇器可以無限制地結合,例如 StackLayout>ContentView>label.email

不支援下列選取器:

  • [attribute]
  • @media@supports
  • :::

注意

不支援特定性和特定性覆寫。

如果兩個以上的 CSS 規則指向相同的元素,則具有最高特定性的選取器會優先,且其樣式宣告會套用至元素。 特定度演算法 計算 CSS 選取器的權數,以判斷哪些規則會從競爭的 CSS 宣告套用至元素。

屬性參考

.NET MAUI 支援下列 CSS 屬性(在 Values 數據行中,類型 斜體,而字元串常值則為 gray):

財產 適用於 價值觀
align-content FlexLayout stretch | center | start | end | spacebetween | spacearound | spaceevenly | flex-start | flex-end | space-between | space-around | initial align-content: space-between;
align-items FlexLayout stretch | center | start | end | flex-start | flex-end | initial align-items: flex-start;
align-self VisualElement auto | stretch | center | start | end | flex-start | flex-end | initial align-self: flex-end;
background-color VisualElement 色彩 | initial background-color: springgreen;
background-image Page 字串 | initial background-image: bg.png;
border-color BorderButtonFrameImageButton 色彩 | initial border-color: #9acd32;
border-radius Border、、 BoxViewButtonFrameImageButton | initial border-radius: 10;
border-width BorderButtonImageButton | initial border-width: .5;
color ActivityIndicatorBoxViewButtonCheckBoxDatePickerEditorEntryLabelPickerProgressBarSearchBarSwitchTimePicker 色彩 | initial color: rgba(255, 0, 0, 0.3);
column-gap Grid | initial column-gap: 9;
direction VisualElement ltr | rtl | inherit | initial direction: rtl;
flex-direction FlexLayout column | columnreverse | row | rowreverse | row-reverse | column-reverse | initial flex-direction: column-reverse;
flex-basis VisualElement float | auto | initial。 此外,範圍 0% 到 100% 的百分比可以使用 % 符號來指定。 flex-basis: 25%;
flex-grow VisualElement 浮動 | initial flex-grow: 1.5;
flex-shrink VisualElement 浮動 | initial flex-shrink: 1;
flex-wrap VisualElement nowrap | wrap | reverse | wrap-reverse | initial flex-wrap: wrap-reverse;
font-family ButtonDatePickerEditorEntryLabelPickerSearchBarTimePickerSpan 字串 | initial font-family: Consolas;
font-size ButtonDatePickerEditorEntryLabelPickerSearchBarTimePickerSpan | initial font-size: 12;
font-style ButtonDatePickerEditorEntryLabelPickerSearchBarTimePickerSpan bold | italic | initial font-style: bold;
height VisualElement | initial height: 250;
justify-content FlexLayout start | center | end | spacebetween | spacearound | spaceevenly | flex-start | flex-end | space-between | space-around | initial justify-content: flex-end;
letter-spacing ButtonDatePickerEditorEntryLabelPickerSearchBarSearchHandlerSpanTimePicker | initial letter-spacing: 2.5;
line-height LabelSpan | initial line-height: 1.8;
margin View 厚度 | initial margin: 6 12;
margin-left View 厚度 | initial margin-left: 3;
margin-top View 厚度 | initial margin-top: 2;
margin-right View 厚度 | initial margin-right: 1;
margin-bottom View 厚度 | initial margin-bottom: 6;
max-lines Label 整數 | initial max-lines: 2;
min-height VisualElement | initial min-height: 50;
min-width VisualElement | initial min-width: 112;
opacity VisualElement | initial opacity: .3;
order VisualElement 整數 | initial order: -1;
padding ButtonImageButtonLayoutPage 厚度 | initial padding: 6 12 12;
padding-left ButtonImageButtonLayoutPage | initial padding-left: 3;
padding-top ButtonImageButtonLayoutPage | initial padding-top: 4;
padding-right ButtonImageButtonLayoutPage | initial padding-right: 2;
padding-bottom ButtonImageButtonLayoutPage | initial padding-bottom: 6;
position FlexLayout relative | absolute | initial position: absolute;
row-gap Grid | initial row-gap: 12;
text-align EntryEntryCellLabelSearchBar left | top | right | bottom | start | center | middle | end | initial。 在從右至左的環境中,應避免 leftright text-align: right;
text-decoration LabelSpan none | underline | strikethrough | line-through | initial text-decoration: underline, line-through;
text-transform ButtonEditorEntryLabelSearchBarSearchHandler none | default | uppercase | lowercase | initial text-transform: uppercase;
transform VisualElement nonerotaterotateXrotateYscalescaleXscaleYtranslatetranslateXtranslateYinitial transform: rotate(180), scaleX(2.5);
transform-origin VisualElement | initial transform-origin: 7.5, 12.5;
vertical-align Label left | top | right | bottom | start | center | middle | end | initial vertical-align: bottom;
visibility VisualElement true | visible | false | hidden | collapse | initial visibility: hidden;
width VisualElement | initial width: 320;

注意

initial 是所有屬性的有效值。 它會清除從另一個樣式設定的值(重設為預設值)。

不支援下列屬性:

  • all: initial
  • 版面配置屬性(方塊或方格)。
  • 速記屬性,例如 fontborder

此外,沒有 inherit 值,因此不支持繼承。 因此,您無法在版面配置上設定 font-size 屬性,並預期配置中的所有 Label 實例都繼承值。 其中一個例外狀況是 direction 屬性,其預設值為 inherit

重要

無法使用 CSS 來選取 Span 元素。

.NET MAUI 特定屬性

也支援下列 .NET MAUI 特定 CSS 屬性(在 數據行中,類型 斜體,而字串常值則為 gray):

財產 適用於 價值觀
-maui-bar-background-color NavigationPageTabbedPage 色彩 | initial -maui-bar-background-color: teal;
-maui-bar-text-color NavigationPageTabbedPage 色彩 | initial -maui-bar-text-color: gray
-maui-horizontal-scroll-bar-visibility ScrollView default | always | never | initial -maui-horizontal-scroll-bar-visibility: never;
-maui-max-length EntryEditorSearchBar 整數 | initial -maui-max-length: 20;
-maui-max-track-color Slider 色彩 | initial -maui-max-track-color: red;
-maui-min-track-color Slider 色彩 | initial -maui-min-track-color: yellow;
-maui-orientation ScrollViewStackLayout horizontal | vertical | both | initialboth僅支援 ScrollView -maui-orientation: horizontal;
-maui-placeholder EntryEditorSearchBar 引述文字 | initial -maui-placeholder: Enter name;
-maui-placeholder-color EntryEditorSearchBar 色彩 | initial -maui-placeholder-color: green;
-maui-spacing StackLayout | initial -maui-spacing: 8;
-maui-shadow VisualElement 有效格式為:color、offsetX、offsetY | offset X,offsetY,radius,color | offset X,offsetY,radius,color,opacity -maui-shadow: #000000 4 4;
-maui-thumb-color SliderSwitch 色彩 | initial -maui-thumb-color: limegreen;
-maui-vertical-scroll-bar-visibility ScrollView default | always | never | initial -maui-vertical-scroll-bar-visibility: always;
-maui-vertical-text-alignment Label start | center | end | initial -maui-vertical-text-alignment: end;
-maui-visual VisualElement 字串 | initial -maui-visual: material;

.NET MAUI Shell 特定屬性

也支援下列 .NET MAUI Shell 特定 CSS 屬性(在 欄中,類型是 斜體,而字串則是 gray):

財產 適用於 價值觀
-maui-flyout-background Shell 色彩 | initial -maui-flyout-background: red;
-maui-shell-background Element 色彩 | initial -maui-shell-background: green;
-maui-shell-disabled Element 色彩 | initial -maui-shell-disabled: blue;
-maui-shell-foreground Element 色彩 | initial -maui-shell-foreground: yellow;
-maui-shell-tabbar-background Element 色彩 | initial -maui-shell-tabbar-background: white;
-maui-shell-tabbar-disabled Element 色彩 | initial -maui-shell-tabbar-disabled: black;
-maui-shell-tabbar-foreground Element 色彩 | initial -maui-shell-tabbar-foreground: gray;
-maui-shell-tabbar-title Element 色彩 | initial -maui-shell-tabbar-title: lightgray;
-maui-shell-tabbar-unselected Element 色彩 | initial -maui-shell-tabbar-unselected: cyan;
-maui-shell-title Element 色彩 | initial -maui-shell-title: teal;
-maui-shell-unselected Element 色彩 | initial -maui-shell-unselected: limegreen;

顏色

支援下列 color 值:

  • X11 色彩,其符合 CSS 色彩和 .NET MAUI 色彩。 這些色彩值不區分大小寫。
  • 十六進位色彩:#rgb#argb#rrggbb#aarrggbb
  • rgb 色彩:rgb(255,0,0)rgb(100%,0%,0%)。 值的範圍為 0-255,或 0%-100%。
  • rgba 色彩:rgba(255, 0, 0, 0.8)rgba(100%, 0%, 0%, 0.8)。 不透明度值位於 0.0-1.0 範圍內。
  • hsl 色彩:hsl(120, 100%, 50%)。 h 值介於 0-360 的範圍內,而 s 和 l 介於 0%-100%範圍內。
  • hsla 色彩:hsla(120, 100%, 50%, .8)。 不透明度值位於 0.0-1.0 範圍內。

厚度

支援一、二、三或四個 thickness 值,每個值會以空格符分隔:

  • 單一值表示統一粗細。
  • 兩個值表示垂直厚度和水平厚度。
  • 三個值表示上端厚度、水平(左和右)厚度、然後是下端厚度。
  • 四個值表示上、右、下、左的厚度。

注意

CSS thickness 值與 XAML Thickness 值不同。 例如,在 XAML 中,雙值 Thickness 表示水平和垂直粗細,而四值 Thickness 則表示左、上、右、下粗細。 此外,XAML Thickness 值會以逗號分隔。

Functions

您可以分別使用 linear-gradient()radial-gradient() CSS 函式來指定線性和星形漸層。 這些函式的結果應該指派給 控件的 background 屬性。