Removing Row and Column Spacing from Xamarin.Forms Grid

Xamarin XAML

4 years ago

Xamarin.Forms Grid allows us to specify spacing between individual rows and columns using RowSpacing and ColumnSpacing properties. While this is no doubt a useful feature, the unfortunate fact is that these are not set to 0 by default.

The problem

If you check the source code on GitHub, you can find the following dependency property declarations:

The default value is 6 for both properties, which means all Grids you create will feature this inner spacing by default. Consider the following Grid:

This XAML yields a rather nice logo, but it usually is not what we want, especially if we want a pixel-perfect layout:

Default Grids spacing in action

Default Grids spacing in action

Setting RowSpacing and ColumnSpacing to 0 solves the problem immediately, but it is easy to forget to do it. How could we do it more generally?

Project-wide solution

Who are we gonna call to resolve our problem? Styles! Defining a default Style targeting a specific element type is easy. To make it work project-wide, we can put it in <Application.Resources> in App.xaml of our shared project or .NET Standard library:

Et voilà! All Grids in our project are now spacing-less!

No spacing, no copyright infringement intended

No spacing, no copyright infringement intended

Using ResourceDictionary

To improve the reusability of our solution, we can move our style to a separate resource dictionary file To do that we create a new empty XAML file. There is no built-in template for this type of XAML file, so you can start with a ContentView template for example and rewrite appropriately. I named my dictionary Reset.xaml and its XAML looks like this:

The code-behind is straightforward as well:

Now we include the file in the <Application.Resources> resource dictionary:

When we rerun the app, it will look the same as before, but ResourceDictionary now allows us to better organize our resources. There is no problem in putting resource dictionaries in a separate assembly which can be reused across multiple apps. To learn even more tricks, check out the official blog post from Xamarin and documentation.


The non-zero default of RowSpacing and ColumnSpacing properties can be a bit confusing, especially for developers coming from WPF and UWP development. Our default style helped us avoid the distinction. Refactoring to ResourceDictionary opens the door for better resource organization and potential of storing a set of multiple "reset" styles in one location.