Xamarin.Forms: Solving the mystery of Grid.Children.Add(left,right,top,bottom)

The Xamarin.Forms Grid layout has three methods for adding Child views to the grid. Two of them allow you to specify the location:

Children.Add(left, top);

Children.Add(left, right, top, bottom);

The first variant is fairly simple: It just takes a column and a row. 

But the second variant, is a little more complicated.  It was probably not meant to be complicated, but due to the naming of the parameters and the lack of documentation on this particular method, makes its use non-intuitive.  I even filed a bug because it was not doing what it says it is supposed to do – or so I thought.

It turns out that it does indeed work properly, assuming you know what the parameters actually mean.  Here is what the method actually needs:

Children.Add(left, right, rowSpan, columnSpan);

We actually had a conversation about this issue a few months back on the Xamarin forums and Till Ballendat gave a great explanation as to the proper use of the method and offered an alternative method extension to make it easier to visualize.  Here is his solution:

public static void AddChild(this Grid grid, View view, int row, int column,

int rowspan = 1, int columnspan = 1) { if (row < 0) throw new ArgumentOutOfRangeException("row"); if (column < 0) throw new ArgumentOutOfRangeException("column"); if (rowspan <= 0) throw new ArgumentOutOfRangeException("rowspan"); if (columnspan <= 0) throw new ArgumentOutOfRangeException("columnspan"); if (view == null) throw new ArgumentNullException("view"); Grid.SetRow((BindableObject)view, row); Grid.SetRowSpan((BindableObject)view, rowspan); Grid.SetColumn((BindableObject)view, column); Grid.SetColumnSpan((BindableObject)view, columnspan); grid.Children.Add(view); }

This came up again this week and with Till’s permission, I’m posting it here for a bit better visibility should others run into the issue.