A few Xamarin.Forms xaml OnPlatform tips & tricks

I’ve been working on some Xamarin forms mobile apps lately, and came across a few tips & tricks I thought I’d share. There are a few platform specific quirks that have to be worked around to get a good looking app on each platform. Luckily, xamarin forms has the OnPlatform thing that can be used.

First is the classic example of where to use OnPlatform, the title bar on iOS. It’s 20 pixels tall, and your app will look terrible if you don’t avoid it:


<ContentPage.Padding>
<OnPlatform x:TypeArguments="Thickness">
<OnPlatform.iOS>
0, 20, 0, 0
</OnPlatform.iOS>
<OnPlatform.Android>
0, 0, 0, 0
</OnPlatform.Android>
<OnPlatform.WinPhone>
0, 0, 0, 0
</OnPlatform.WinPhone>
</OnPlatform>
</ContentPage.Padding>

 

Another thing I’ve noticed is the grid control on WinPhone. WinPhone has a hidden border around it’s controls, so if you use RowSpacing and ColumnSpacing of 0 it will actually have big fat borders around your stuff. You can use negative row & column spacing to make it look the same as other platforms:


<Grid.RowSpacing>
<OnPlatform x:TypeArguments="x:Double">
<OnPlatform.iOS>
1
</OnPlatform.iOS>
<OnPlatform.Android>
1
</OnPlatform.Android>
<OnPlatform.WinPhone>
-22
</OnPlatform.WinPhone>
</OnPlatform>
</Grid.RowSpacing>

<Grid.ColumnSpacing>
<OnPlatform x:TypeArguments="x:Double">
<OnPlatform.iOS>
1
</OnPlatform.iOS>
<OnPlatform.Android>
1
</OnPlatform.Android>
<OnPlatform.WinPhone>
-22
</OnPlatform.WinPhone>
</OnPlatform>
</Grid.ColumnSpacing>

 

Lastly, the Editor control on WinPhone is currently pretty messed up. The background changes color from black to white depending on whether it has focus or not, but the text doesn’t change color so it’s unreadable most of the time. To force it to be white all the time:

<Editor.BackgroundColor>
<OnPlatform x:TypeArguments="Color">
<OnPlatform.WinPhone>
White
</OnPlatform.WinPhone>
</OnPlatform>
</Editor.BackgroundColor>

So there you go… keep in mind Xamarin development is a moving target, so these tips&tricks are probably obsolete by the time you read this 😛

Cheers!

Advertisements