Xamarin.Forms使用級聯樣式表設定應用程式樣式表 (CSS)

Download Sample 下載範例

Xamarin.Forms 支援使用級聯樣式表 (CSS) 設定可視化元素的樣式。

Xamarin.Forms 應用程式可以使用 CSS 來設定樣式。 樣式表單包含規則清單,每個規則都包含一或多個選取器和宣告區塊。 宣告區塊是由大括弧中的宣告清單所組成,每個宣告都包含屬性、冒號和值。 當區塊中有多個宣告時,分號會插入為分隔符。 下列程式代碼範例顯示一些 Xamarin.Forms 符合規範的 CSS:

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

^contentpage {
    background-color: lightgray;
}

#listView {
    background-color: lightgray;
}

stacklayout {
    margin: 20;
}

.mainPageTitle {
    font-style: bold;
    font-size: medium;
}

.mainPageSubtitle {
    margin-top: 15;
}

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

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

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

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

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

注意

目前,XAML 樣式可能的所有樣式都無法使用 CSS 來執行。 不過,XAML 樣式可用來補充目前不受 支援 Xamarin.Forms之屬性的 CSS。 如需 XAML 樣式的詳細資訊,請參閱 使用 XAML 樣式設定 Xamarin.Forms 應用程式樣式

MonkeyAppCSS 範例示範如何使用 CSS 來設定簡單應用程式的樣式,並顯示在下列螢幕快照中:

MonkeyApp Main Page with CSS styling

MonkeyApp Detail Page with CSS styling

使用樣式表單

將樣式表單新增至解決方案的程式如下:

  1. 將空白 CSS 檔案新增至 .NET Standard 連結庫專案。
  2. 將 CSS 檔案的建置動作設定為 EmbeddedResource

載入樣式表單

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

注意

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

XAML

在加入 ResourceDictionary至 之前,可以先載入樣式表單並剖StyleSheet析 類別:

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

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

警告

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

或者,在將樣式表單內CDATA嵌至 ResourceDictionary區段之前,可以先載入和剖StyleSheet析類別:

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

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

C#

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

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 器專屬於 Xamarin.Forms,且不屬於 CSS 規格的一部分。

依名稱選取專案

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

#listView {
    background-color: lightgray;
}

這個選取器會識別屬性設定為listView的專案StyleId。 不過,如果未 StyleId 設定 屬性,選取器會回復為使用 x:Name 專案的 。 因此,在下列 XAML 範例中, #listView 選取器會識別 ListView 屬性 x:Name 設定為 listView的 ,並將它的背景色彩設定為 lightgray

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

選取具有特定類別屬性的專案

您可以使用區分大小寫 .class 的選取器來選取具有特定類別屬性的專案:

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

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

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

<ContentPage ...>
    <ContentPage.Resources>
        <StyleSheet Source="/Assets/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="/Assets/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。 因此,在下列 XAML 範例中, stacklayout>image 選取器會識別 Image 為的直接子系 StackLayout,並將其高度和寬度設定為 200。

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

注意

選取 element>element 器要求子專案是 父系的直接 子系。

選取器參考

支援 Xamarin.Forms下列 CSS 選取器:

選取器 範例 描述
.class .header 選取包含 StyleClass 『header』 屬性的所有元素。 請注意,此選取器區分大小寫。
#id #email 選取所有設定為email的專案StyleId。 如果未 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 選取具有 StackLayout 作為直接父代的所有Label元素。 請注意,此選取器不區分大小寫。
element+element label+entry 直接選取 之後Label的所有Entry專案。 請注意,此選取器不區分大小寫。
element~element label~entry 選取前面加上 Label的所有Entry專案。 請注意,此選取器不區分大小寫。

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

提示

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

目前不支援下列選取器:

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

注意

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

屬性參考

支援下列 CSS 屬性(在 Values 資料Xamarin.Forms行中,類型為斜體,而字串常值為 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 color | initial background-color: springgreen;
background-image Page string | initial background-image: bg.png;
border-color Button、 、 FrameImageButton color | initial border-color: #9acd32;
border-radius BoxView、 、 ButtonFrameImageButton double | initial border-radius: 10;
border-width Button, ImageButton double | initial border-width: .5;
color ActivityIndicatorBoxViewButtonCheckBox、、EditorLabelProgressBarEntryPickerDatePicker、、 SearchBarSwitchTimePicker color | initial color: rgba(255, 0, 0, 0.3);
column-gap Grid double | 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 | | autoinitial。 此外,範圍 0% 到 100% 的百分比可以使用符號來指定 % flex-basis: 25%;
flex-grow VisualElement float | initial flex-grow: 1.5;
flex-shrink VisualElement float | initial flex-shrink: 1;
flex-wrap VisualElement nowrap | wrap | reverse | wrap-reverse | initial flex-wrap: wrap-reverse;
font-family ButtonDatePickerEditorEntryLabelPickerSearchBarTimePickerSpan string | initial font-family: Consolas;
font-size ButtonDatePickerEditorEntryLabelPickerSearchBarTimePickerSpan double | namedsize | initial font-size: 12;
font-style ButtonDatePickerEditorEntryLabelPickerSearchBarTimePickerSpan bold | italic | initial font-style: bold;
height VisualElement double | initial min-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 ButtonDatePickerEditorEntryLabelPickerSearchBar、、SearchHandler、、 SpanTimePicker double | initial letter-spacing: 2.5;
line-height Label, Span double | 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 int | initial max-lines: 2;
min-height VisualElement double | initial min-height: 50;
min-width VisualElement double | initial min-width: 112;
opacity VisualElement double | initial opacity: .3;
order VisualElement int | initial order: -1;
padding Button、 、 ImageButtonLayoutPage 厚度 | initial padding: 6 12 12;
padding-left Button、 、 ImageButtonLayoutPage double | initial padding-left: 3;
padding-top Button、 、 ImageButtonLayoutPage double | initial padding-top: 4;
padding-right Button、 、 ImageButtonLayoutPage double | initial padding-right: 2;
padding-bottom Button、 、 ImageButtonLayoutPage double | initial padding-bottom: 6;
position FlexLayout relative | absolute | initial position: absolute;
row-gap Grid double | initial row-gap: 12;
text-align Entry、 、 EntryCellLabelSearchBar left | top | right | bottom | start | center | middle | end | initial. left 應該避免在右至左環境中使用和 right text-align: right;
text-decoration Label, Span none | underline | strikethrough | line-through | initial text-decoration: underline, line-through;
text-transform ButtonEditor、、 EntryLabelSearchBarSearchHandler none | default | uppercase | lowercase | initial text-transform: uppercase;
transform VisualElement nonerotaterotateXrotateYscalescaleXscaleYtranslate、、 translateXtranslateYinitial transform: rotate(180), scaleX(2.5);
transform-origin VisualElement double、double | 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 double | initial min-width: 320;

注意

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

目前不支援下列屬性:

  • all: initial.
  • 版面配置屬性(方塊或方格)。
  • 速記屬性,例如 font、 和 border

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

目標 Span 專案有一個已知問題,導致範圍無法同時以元素和名稱作為 CSS 樣式的目標(使用 # 符號)。 專案 Span 衍生自 GestureElement,其沒有 StyleClass 屬性,因此範圍不支援 CSS 類別目標。 如需詳細資訊,請參閱 無法將 CSS 樣式套用至 Span 控件

Xamarin.Forms 特定屬性

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

屬性 適用於 範例
-xf-bar-background-color NavigationPage, TabbedPage color | initial -xf-bar-background-color: teal;
-xf-bar-text-color NavigationPage, TabbedPage color | initial -xf-bar-text-color: gray
-xf-horizontal-scroll-bar-visibility ScrollView default | always | never | initial -xf-horizontal-scroll-bar-visibility: never;
-xf-max-length Entry、 、 EditorSearchBar int | initial -xf-max-length: 20;
-xf-max-track-color Slider color | initial -xf-max-track-color: red;
-xf-min-track-color Slider color | initial -xf-min-track-color: yellow;
-xf-orientation ScrollView, StackLayout horizontal | vertical | both | initial. both 只有在 上 ScrollView才支援 。 -xf-orientation: horizontal;
-xf-placeholder Entry、 、 EditorSearchBar 引號文字 | initial -xf-placeholder: Enter name;
-xf-placeholder-color Entry、 、 EditorSearchBar color | initial -xf-placeholder-color: green;
-xf-spacing StackLayout double | initial -xf-spacing: 8;
-xf-thumb-color Slider, Switch color | initial -xf-thumb-color: limegreen;
-xf-vertical-scroll-bar-visibility ScrollView default | always | never | initial -xf-vertical-scroll-bar-visibility: always;
-xf-vertical-text-alignment Label start | center | end | initial -xf-vertical-text-alignment: end;
-xf-visual VisualElement string | initial -xf-visual: material;

Xamarin.Forms 殼層特定屬性

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

屬性 適用於 範例
-xf-flyout-background Shell color | initial -xf-flyout-background: red;
-xf-shell-background Element color | initial -xf-shell-background: green;
-xf-shell-disabled Element color | initial -xf-shell-disabled: blue;
-xf-shell-foreground Element color | initial -xf-shell-foreground: yellow;
-xf-shell-tabbar-background Element color | initial -xf-shell-tabbar-background: white;
-xf-shell-tabbar-disabled Element color | initial -xf-shell-tabbar-disabled: black;
-xf-shell-tabbar-foreground Element color | initial -xf-shell-tabbar-foreground: gray;
-xf-shell-tabbar-title Element color | initial -xf-shell-tabbar-title: lightgray;
-xf-shell-tabbar-unselected Element color | initial -xf-shell-tabbar-unselected: cyan;
-xf-shell-title Element color | initial -xf-shell-title: teal;
-xf-shell-unselected Element color | initial -xf-shell-unselected: limegreen;

顏色

支援下列 color 值:

  • X11色彩,符合 CSS 色彩、UWP 預先定義的色彩和 Xamarin.Forms 色彩。 請注意,這些色彩值不區分大小寫。
  • 十六進位色彩:#rgb、、、#rrggbb#argb#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

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

  • 單一值表示統一粗細。
  • 兩個值表示垂直,然後水準粗細。
  • 三個值表示頂端,然後水準 (左和右),然後是底部粗細。
  • 四個值表示頂端、右、下、左粗細。

注意

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

NamedSize

支援下列不區分 namedsize 大小寫的值:

  • default
  • micro
  • small
  • medium
  • large

每個 namedsize 值的確切意義是平臺相依和檢視相依。

函式

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

與 Xamarin.University 搭配的 Xamarin.Forms CSS

Xamarin.Forms 3.0 CSS 影片