Wednesday 16 May 2018

Platform specific

No let's say that we are writing a Xamarin forms app and for some bizarre reason we want our application to have a different background color in our different OS's, let's say for the sake of argument that we wanted:

  • Android background to be Black
  • IOS background to be White
  • UWP background to be DarkGrey

well we could set those values directly in our xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns=""

        <OnPlatform x:TypeArguments="Color">
            <On Platform="Android">Black</On>
            <On Platform="IOS">White</On>
            <On Platform="UWP">DarkGray</On>
        <Label Text="Welcome to Xamarin.Forms!" 
               VerticalOptions="CenterAndExpand" />     

and that's it, our apps background color is now different based on the Platform we are deploying our app to.

there's also a non declarative way to execute platform specific logic using pre-processor directives

public static string GetPlatformName() { string result = "notset"; #if __ANDROID__ result = "Droid"; #elif __IOS__ result = "IOS"; #elif WINDOWS_UWP result = "UWP"; #endif return result; }

these can be leveraged inside of Shared projects to compile separate code for different
Symbol What it represents
#if __MOBILE__ Any mobile project (vs. desktop)
#if __ANDROID__ Xamarin.Android - defined by the compiler
#if __IOS__ Xamarin.iOS - defined by the compiler
#if __MAC__ Xamarin.Mac - defined by the compiler
#if __TVOS__ iOS tvOS - defined by the compiler
#if __WATCHOS__ iOS watchOS - defined by the compiler
#if WINDOWS_UWP Windows 10 UWP - defined in build settings