包含按行和列排列的视图的布局。

StackOverflow 文档

这是 XAML 中典型的 Grid 定义。

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="2*" />
    <RowDefinition Height="*" />
    <RowDefinition Height="200" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
    
  <ContentView Grid.Row="0" Grid.Column="0"/>
  <ContentView Grid.Row="1" Grid.Column="0"/>
  <ContentView Grid.Row="2" Grid.Column="0"/>

  <ContentView Grid.Row="0" Grid.Column="1"/>
  <ContentView Grid.Row="1" Grid.Column="1"/>
  <ContentView Grid.Row="2" Grid.Column="1"/>

</Grid>

代码中定义的相同 Grid 如下所示:

var grid = new Grid();
grid.RowDefinitions.Add (new RowDefinition { Height = new GridLength(2, GridUnitType.Star) });
grid.RowDefinitions.Add (new RowDefinition { Height = new GridLength (1, GridUnitType.Star) });
grid.RowDefinitions.Add (new RowDefinition { Height = new GridLength(200)});
grid.ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (200) });

要向网格添加项目:在 XAML 中:

<Grid>
      
   <--DEFINITIONS...--!>
        
   <ContentView Grid.Row="0" Grid.Column="0"/>
   <ContentView Grid.Row="1" Grid.Column="0"/>
   <ContentView Grid.Row="2" Grid.Column="0"/>

   <ContentView Grid.Row="0" Grid.Column="1"/>
   <ContentView Grid.Row="1" Grid.Column="1"/>
   <ContentView Grid.Row="2" Grid.Column="1"/>

</Grid>

在 C#代码中:

var grid = new Grid();
//DEFINITIONS...
var topLeft = new Label { Text = "Top Left" };
var topRight = new Label { Text = "Top Right" };
var bottomLeft = new Label { Text = "Bottom Left" };
var bottomRight = new Label { Text = "Bottom Right" };
grid.Children.Add(topLeft, 0, 0);
grid.Children.Add(topRight, 0, 1);
grid.Children.Add(bottomLeft, 1, 0);
grid.Children.Add(bottomRight, 1, 1);

对于 HeightWidth,有许多单位可供选择。

  • 自动 - 自动调整大小以适合行或列中的内容。在 C#中指定为 GridUnitType.Auto 或在 XAML 中指定为 Auto。
  • 比例 - 将列和行的大小作为剩余空间的比例。在 C#中指定为值和 GridUnitType.Star,在 XAML 中指定为#*,其中#是你想要的值。使用*指定一行/列将使其填充可用空间。
  • 绝对 - 使用特定的固定高度和宽度值来定义列和行。在 C#中指定为值和 GridUnitType.Absolute,在 XAML 中指定为#,其中#是你想要的值。

注意: 默认情况下,Xamarin.Forms 中列的宽度值设置为自动,这意味着宽度由子项的大小确定。请注意,这与 Microsoft 平台上的 XAML 实现不同,默认宽度为*,这将填充可用空间。