Adicionando visualizações ao Xamarin.Forms Grid programaticamente

No Xamarin.Forms Xaml, é fácil adicionar filhos a um Grid especificando a linha, coluna, extensão de coluna e extensão de linha, mas fazer isso programaticamente é um pouco mais complicado.

Exemplo XAML:

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>

<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width=".2*" />
<ColumnDefinition Width=".2*" />
<ColumnDefinition Width=".5*" />
<ColumnDefinition Width=".1*" />
</Grid.ColumnDefinitions>

<Label Text="Hello" Grid.Row="0" Grid.Column="0" />
<Label Text="World" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="3" />
<Label Text="From Albuquerque, NM" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="5" />
</Grid>

Uma nota sobre IGridList <T>

IGridList <T> .Add () é implementado como Grid.Children.Add () e tem dois overloads.

Add(View view, int left, int top);
Add(View view, int left, int right, int top, int bottom);

Os parâmetros são mapeados para os valores de linha, coluna, extensão de linha e extensão de coluna, assim:

IGridList<T>.Add(view, left, top) == Grid.Children.Add(view, column, row);
IGridList<T>.Add(view, left, right, top, bottom) == Grid.Children.Add(view, column, column+columnSpan, row, row+rowSpan);

Exemplo C #

var grid = new Grid
{
RowDefinitions =
{
new RowDefinition { Height = new GridLength(60, GridUnitType.Absolute) },
new RowDefinition { Height = GridLength.Auto },
}, ColumnDefinitions =
{
new ColumnDefinition { Width = new GridLength(100, GridUnitType.Absolute) },
new ColumnDefinition { Width = new GridLength(.2, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(.2, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(.5, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(.1, GridUnitType.Star) }
}
};


//if right and bottom aren't specified, the column and row spans will be 1
grid
.Children.Add(new Label{Text="Hello"}, 0, 0);

//to start at column 1 and span 4 columns, right needs to be column + column span; 1 + 4 = 5. Since this overload requires values for top and bottom, the row (top) is 0, and the row span is 1; 0 + 1 = 1, so bottom must be 1.
grid
.Children.Add(new Label{Text="World"}, 1, 5, 0, 1);

//column (left) = 0, right = column + column span; 0 + 5 = 6. row (top) = 1, bottom = row + row span; 1 + 1 = 2
grid
.Children.Add(new Label{Text="From Albuquerque, NM"}, 0, 6, 1, 2);