Xamarin.Forms Grid 网格布局

1. 创建项目

启动 Visual Studio,新建一个空白的 Xamarin.Forms 应用,项目名称为:

GridTutorial

2. 创建基本界面

双击打开 MainPage.xaml,删除所有模板代码,替换为以下内容:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GridTutorial.MainPage">
    <Grid Margin="20,35,20,20">
        <Label Text="The Grid has its Margin property set, to control the rendering position of the Grid." />
    </Grid>
</ContentPage>Code language: HTML, XML (xml)

说明

  • 界面由一个 Grid 和一个 Label 组成。
  • 默认情况下,Grid 会将子视图放置在单一位置
  • 因此,如果 Grid 中包含多个子项,通常需要显式定义列和行

3. 指定列和行

3.1 在 Grid 中定义列和行

修改 MainPage.xaml 中的 Grid 声明,定义列和行,并将内容放入指定位置:

<Grid Margin="20,35,20,20">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0.5*" />
        <ColumnDefinition Width="0.5*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="50" />
        <RowDefinition Height="50" />
    </Grid.RowDefinitions>

    <Label Text="Column 0, Row 0" />
    <Label Grid.Column="1"
           Text="Column 1, Row 0" />
    <Label Grid.Row="1"
           Text="Column 0, Row 1" />
    <Label Grid.Column="1"
           Grid.Row="1"
           Text="Column 1, Row 1" />
</Grid>Code language: HTML, XML (xml)

说明

  • 列和行分别通过以下属性定义:
    • ColumnDefinitions:存放 ColumnDefinition 对象的集合
    • RowDefinitions:存放 RowDefinition 对象的集合
  • 每列宽度由 ColumnDefinition.Width 设置
  • 每行高度由 RowDefinition.Height 设置

尺寸设置方式

类型说明
Auto根据内容自动调整大小
比例值(如 *0.5*按剩余空间的比例分配
绝对值(如 50使用固定的设备无关单位

在上面的示例中:

  • 每列宽度为 Grid 的一半(0.5*
  • 每行高度为 50 个设备无关单位

子视图定位

  • 使用从 0 开始的索引
  • 通过附加属性指定位置:
    • Grid.Column
    • Grid.Row
  • 未设置这些属性的子视图,将自动放置在第 0 列、第 0 行

4. 跨列和跨行

4.1 修改 Grid 以使用跨列和跨行

MainPage.xaml 中,修改 Grid 声明:

<Grid Margin="20,35,20,20">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0.5*" />
        <ColumnDefinition Width="0.5*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="50" />
        <RowDefinition Height="30" />
        <RowDefinition Height="30" />
    </Grid.RowDefinitions>

    <Label Grid.ColumnSpan="2"
           Text="This text uses the ColumnSpan property to span both columns." />

    <Label Grid.Row="1"
           Grid.RowSpan="2"
           Text="This text uses the RowSpan property to span two rows." />
</Grid>Code language: HTML, XML (xml)

说明

  • ColumnSpan 附加属性:
    • 用于让子视图跨越多列
    • 示例中设置为 2,表示跨越两列
  • RowSpan 附加属性:
    • 用于让子视图跨越多行
    • 示例中设置为 2,表示跨越两行

5. 总结

本教程介绍了以下内容:

  • 创建 Xamarin.Forms 项目
  • 使用 Grid 布局控件
  • 定义 Grid 的列和行
  • 使用 Grid.ColumnGrid.Row 定位子视图
  • 使用 ColumnSpanRowSpan 实现跨列和跨行布局

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注