Grid In Xamarin.Forms

Basically, grid is used for arranging views into rows and columns. Although StackLayout is good enough, when we want to create some complex layout, it’s better to use Grid. If you have ever seen graph paper, it’s easy for you to learn the Grid in Xamarin Forms.

Grid
Thus, before going into detail, you need to learn important things, which are RowDefinitions, ColumnDefinitions, Height and Width.

After creating the Grid, we first define its rows and later define the height of the rows. Afterwards, we need to define a column and a width of this column.

Let’s look at the code, given below:

  1. <Grid>  
  2.     <Grid.RowDefinitions>  
  3.         <RowDefinition Height="*" />  
  4.         <RowDefinition Height="*" />  
  5.         <RowDefinition Height="*" /> </Grid.RowDefinitions>  
  6.     <Grid.ColumnDefinitions>  
  7.         <ColumnDefinition Width="*" />  
  8.         <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions>  
  9. </Grid>  
The important point here is that, you’ll see a Height="*" and a Width="*". Don’t confuse these with asterisk (*). It means specifying one row or a column with Height="*" or Width="*" will cause it to fill the available space.

Now, let’s add four different BoxView controls in XAML page and give the reference of the Grid.Row and Grid.Columns.The important point to remember is that, we’ll set Grid.Row = 0 and Grid. Column = 0 for the first row and first column. To be precise, rows and columns starts with 0 not 1, just like arrays.

code

Let’s try to run it and see what’s happening on the device screen. I’ll test it on an Android device. The result will be the same on iOS as well as in Windows device family.

result

It makes sense, but we have space left for one BoxView. If we want to expand the Blue BoxView, we’ll add Grid.ColumnSpan="2" and it will expand it to two columns and the same concept applies to rows, as well.

code

Hope it’ll make sense. Let’s run it one more time and try to figure out what’s actually happening.

result

 

Up Next
    Ebook Download
    View all
    Learn
    View all