StackLayout

堆棧式地放置內(nèi)容
可以在xaml中完成視圖,也可以在cs代碼中完成視圖

Xamarin的所有視圖和布局都是可以
1.在xaml中完成
2.在cs代碼中完成視圖
(類比WPF)

示例

在cs代碼中完成視圖

var red = new Label
{
    Text = "Stop",
    BackgroundColor = Color.Red,
    FontSize = 20
};
var yellow = new Label
{
    Text = "Slow down",
    BackgroundColor = Color.Yellow,
    FontSize = 20
};
var green = new Label
{
    Text = "Go",
    BackgroundColor = Color.Green,
    FontSize = 20
};

//內(nèi)容
Content = new StackLayout
{
    //間距
    Spacing = 10,
    Children = { red, yellow, green }
};

在xaml中完成視圖

這里注意默認(rèn)生成的是Page,不是ContentPage,要手動(dòng)修改,不然無效

<ContentPage 
    x:Class="XamarinDemo.DemoPages.StackLayoutExample"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamarinDemo.DemoPages"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" Padding="20">
    <StackLayout Spacing="10">
        <Label Text="Stop" BackgroundColor="Red" Font="20"/>
        <Label Text="Slow down" BackgroundColor="Yellow" Font="20" />
        <Label Text="Go" BackgroundColor="Green" Font="20" />
    </StackLayout>
</ContentPage>

效果

1

指定方向

Orientation:擺放方向

//垂直(從上到下)
Vertical = 0,
//水平(從左往右)
Horizontal = 1

VerticalOptions:垂直(上下)方向的選項(xiàng)
HorizontalOptions:水平(左右)方向的選項(xiàng)

Start
Center
End
Fill
StartAndExpand
CenterAndExpand
EndAndExpand
FillAndExpand

設(shè)置方向示例

//內(nèi)容
Content = new StackLayout
{
    //間距
    Spacing = 10,
    //垂直方向上,從底部出發(fā)
    VerticalOptions = LayoutOptions.End,
    //堆放三個(gè)Label的方向是水平
    Orientation = StackOrientation.Horizontal,
    //水平方向上,從開始(左邊)出發(fā)
    HorizontalOptions = LayoutOptions.Start,
    Children = { red, yellow, green }
};

效果

2

示例代碼

https://github.com/zLulus/NotePractice/tree/dev3/Xamarin.Forms/XamarinDemo/XamarinDemo/XamarinDemo/DemoPages 的StackLayoutExample

Children

StackLayout的Children定義是

// 摘要:
//     Gets an IList<View> of child element of the Layout.
public IList<T> Children { get; }

所以Children可以裝下View的集合,不止是Label,也可以是ListView等等

示例

var listView = new Xamarin.Forms.ListView
{
    RowHeight = 40
};
listView.ItemsSource = new string[]
{
    "Buy pears",
    "Buy oranges",
    "Buy mangos",
    "Buy apples",
    "Buy bananas"
};
Content = new StackLayout
{
    VerticalOptions = LayoutOptions.FillAndExpand,
    Children = { listView }
};

示例代碼

https://github.com/zLulus/NotePractice/tree/dev3/Xamarin.Forms/XamarinDemo/XamarinDemo/XamarinDemo/DemoPages 的StackLayoutExample 的ListViewInStackLayout

Tips

同時(shí)設(shè)置xaml和cs代碼,哪個(gè)在后面,以哪個(gè)為準(zhǔn),相當(dāng)于被覆蓋了

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容