Xamarin.Forms OnPlatform And RuntimePlatform

To display a different element, or set a property to a different value, depending upon which platform you are on, you use the OnPlatform, or TargetPlatform enum. You would use this, as sometimes elements just don’t work well across two or more platforms. But you can easily do this in XAML or C# (code behind). One of the most common examples is setting a top padding of 20, on iOS to account for the status bar. These properties have slightly changed since 2.3.4, and it is now recommended to use the below.


OnPlatform allows you to change a property in XAML, depending upon platform. Use the OnPlatform element, set the TypeArguments to the actual type of the property you want to set, in this case Padding is of type Thickness. In the element, add On, and set the property Platform, to the platforms you want. This is a comma delimited string.

        <OnPlatform x:TypeArguments="Thickness">
            <On Platform="Android, UWP">0</On>
            <On Platform="iOS">0,20,0,0</On>

If you don’t set, the property isn’t changed, and it just uses its default. If you want to know what values you can set, lets look at the Device class and RuntimePlatform property.


Device.OS and the TargetPlatform enum is now obsolete, and it is now recommended to use Device.RuntimePlatform. This is just a string value, and there are a number of platforms you compare against in the Device class.

    case Device.iOS:
        this.Padding = new Thickness(0,20,0,0);
    case Device.Android:
    case Device.UWP:   
    case Device.macOS:
        // This is just an example. You wouldn't actually need to do this, since Padding is already 0 by default.
        this.Padding = new Thickness(0);

Just search the Device class with intellisense to find the platform you need. The most common ones are shown in the example.


I actually originally complained about doing Device.RuntimePlatform as a string, instead of an enum with Flags. However the string won out. You do lose the advantage of having a set list of platforms supported in an easy namespace and must guess some constants names. It’s not hard, but just another hurdle to newcomers. Overall an acceptable solution. It is meant to allow easy expansion, where in the future more platforms can be easily added.


  1. Toby Smith

    But what if I want to define my own default value within XAML that does not match the default value provided by the VisualElement? Let’s say I want do define a Color value that is different on iOS, but should be used by default on any other platform? Is there a default attribute to use?

    1. Adam Pedley

      You will need to set the On Platform for all the other platforms you have. Platform=”Android, UWP” and then set your default there.

      If you set the property first, then use On Platform, it ignores the property you originally set.