Xamarin OnPlatform

OnPlatform in Code Behind

Scratching your head how to use Xamarin’s OnPlatform directive in code-behind? Here’s how.

Background

When using the Xamarin platform to write apps for Android and iOS you must sometimes distinquish between the two. It could be layout specifics, or implementation specifics. Regardless of reason, the Xamarin platform provides a very handy Xaml ‘directive’ called OnPlatform. Use it like this:

<Setter Property="BackgroundColor">
    <OnPlatform x:TypeArguments="Color"> 
        <On Platform="iOS">Green</On>
        <On Platform="Android">Red</On>
    </OnPlatform>
</Setter>

How to

Here it is used as part of a style declared in a resource section in xaml. As you can see it takes a string argument, the platform name. Now this is all fine and dandy, but how do you use it in code-behind? It is quite easy, although the code may look contrived at first. Here’s how:

var fontToUse = new FontImageSource
{
    FontFamily = (OnPlatform<string>)Application.Current.Resources["FontAwesomeSolid"],
    Color = (Color)Application.Current.Resources["DefaultBackground"]
};

The second line, where Color is assigned, is probably familiar. We’re looking up a xaml resource by name, and there’s a type cast since we know it’s of type Color. The Font family assignment is effectively doing the same thing, only the type cast looks a bit different. The trick here is to cast it to a OnPlatform<string> object. An implicit conversion takes place, so it will work, as long as you specify that type cast, as the type to cast to must be known at compile time.

Summary

Using the OnPlatform directive is as easy in Xaml as in Code Behind, as long as you know how, which I guess is always the trick. Well, now you know 🙂


Posted

in

, ,

by

Tags: