Taoffi's blog

prisonniers du temps

Xamarin forms – the OnPlatform<T> heavens!

Xamarin forms offer this class (OnPlatform<T>) of great help to adapt your code (either c# or Xaml) to the current runtime device's platform.

So you may write:

string helloDevice = Device.OnPlatform<string>(
            "Hello iOS", "Hello Droid", "Hello Win Phone");

 At runtime, on iOS, your string would have the related platform value:

In Xaml, you specify the type to which the OnPlatform should act and the values for each platform:

<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>

The main difficulty in Xaml is that you should know exactly the Type to pass as TypeArgument.

For system known types, you should use the x: prefix like in:

x:TypeArguments="x:String"
x:TypeArguments="x:Double"
x:TypeArguments="x:Int32"

For Xamarin Forms objects properties and types, it is easy to use the Visual Studio Object Browser to obtain the correct information:

Here, for instance, you know that the Padding is of type Xamarin Forms Thickness:

    <OnPlatform x:TypeArguments="Thickness">

 

Comments are closed