Recently I’ve been talking with some people that are having some difficulties understanding Grids, and to achieve similar things they use other kinds of layout.
In this article, I’m going to explain step by step how to use a grid, why, and what you can achieve with it.
Let’s start with the basics
A grid is a layout type that allows you to create designs using Row/Columns.
Create a Grid is really simple you just have to:
1-Add the Tag ‘Grid’
var grid = new Grid();
2-Add the size of each cell
To define the size, there are 3 ways to do it:
It is a fixed size, so you can add any number to the Wight/Height parameter.
The Row/Column will adapt to the child size.
As you can see, the black box has a Height of 80, so the row takes that size.
It expands proportionally to the space size.
So, for example, if you want to have different boxes that occupy a height of 50%, 20%, 30%, the code will be something like this:
Note: In XAML instead of 1* you can use just *
To add each row/column to the grid, we have two properties: Grid.RowDefinitions (To add rows) and Grid.ColumnDefinitions (To add columns), both are collections that receive a list of each Row and Column definition. Also, you can mix all the size type properties we saw before.
3-Add an element
To add an element to a box view you just have to specify in what Column and Row you want to place it, for example:
If we want to add the pink box view we saw in the image before and place it in the Column 0/Row 0:
To get the UI we saw before:
If you want your cell to occupy more than one row/column you can use the property Row.Span or Column.Span, and specify which cell you want to span.
For example, if you want to remove the green box and expand your pink box to the next column (Column 1), the code would look like:
Note: Check that instead of expanding until 1 we are expanding until 2. If you expand until 1 it won’t have any effect because the actual cell in the position 0 is expanded until 1 by default.
If you want to have more spacing between Columns and Rows you can use the properties RowSpacing and ColumnSpacing.
Why use Grids
- Performance Improvement: Having a screen with a lot of layouts can make the rendering slower, so this is why sometimes you can see an app running slower. To improve it a better approach is to use a Grid because you will only have one layout with multiple children.
A good reference about it: https://michaelridland.com/xamarin/hacking-the-xamarin-forms-layout-system-for-fun-and-profit/
What else we can achieve using Grids
- Responsive UI
- Put an element over the other
- Tablet UI Effect
That’s all for now.