Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms OnPlatform in Xaml

I have the following C# code:

var footer = new StackLayout()
            { BackgroundColor = Device.OnPlatform(Color.FromRgb(225, 240, 251), Color.FromRgb(225, 240, 251), Color.Black),
            };

How can I translate that into Xamarin Xaml, more importantly the Device Platform specifics for the FromRgb?

I have the following XAML so far... again, it's the FromRgb that's stumping me.

<StackLayout.BackgroundColor>
    <Color>
        <OnPlatform x:TypeArguments="Color"></OnPlatform>
    </Color>
</StackLayout.BackgroundColor>

UPDATE 14/02/2015

I've just tried the answer below and I have the following but it's not updating the background colour for either iOS or Windows Phone. If I add the Background Color to the root StackLayout element it works...:

<StackLayout HorizontalOptions="FillAndExpand">
    <StackLayout.BackgroundColor>
      <Color>
        <OnPlatform x:TypeArguments="Color">
          <OnPlatform.WinPhone>#51C0D4</OnPlatform.WinPhone>
          <OnPlatform.iOS>#51C0D4</OnPlatform.iOS>
        </OnPlatform>
      </Color>
    </StackLayout.BackgroundColor>
    <Label Text=""></Label>
    <StackLayout Orientation="Horizontal"  VerticalOptions="EndAndExpand" HorizontalOptions="FillAndExpand">
      <StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand">
      <Button Text="Login"></Button>
      <Button Text="Sign Up"></Button>
      </StackLayout>
    </StackLayout>
  </StackLayout>
like image 399
dotnethaggis Avatar asked Feb 13 '15 17:02

dotnethaggis


2 Answers

You're almost there. The default converter takes care of converting the color from either a named color (e.g. White, Red, etc.) or a hex color (e.g.: #FF0000).

<StackLayout.BackgroundColor>
    <OnPlatform x:TypeArguments="Color">
        <OnPlatform.iOS>#FF0000</OnPlatform.iOS>
        <OnPlatform.Android>#00FF00</OnPlatform.Android>
    </OnPlatform>
</StackLayout.BackgroundColor>
like image 80
Andy Hopper Avatar answered Oct 14 '22 08:10

Andy Hopper


Newer version syntax of OnPlatform is slightly different

In Xaml:

 <ResourceDictionary>
            <OnPlatform x:Key="SwitchOnColor"  x:TypeArguments="Color" >
                <On Platform="iOS|Android" >#0000FF</On>
                <On Platform="UWP">#FF0000</On>
            </OnPlatform>
 </ResourceDictionary> 

In code:

 switch (Device.RuntimePlatform)
 {
     case "iOS":
     break;
     case "Android":
     break;
     case "UWP":
     break;
     default:
     break;
 }
like image 32
Yuri S Avatar answered Oct 14 '22 09:10

Yuri S