简体   繁体   中英

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>

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

<StackLayout.BackgroundColor>
    <OnPlatform x:TypeArguments="Color">
        <OnPlatform.iOS>#FF0000</OnPlatform.iOS>
        <OnPlatform.Android>#00FF00</OnPlatform.Android>
    </OnPlatform>
</StackLayout.BackgroundColor>

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

You can do this also:

<ContentView>
        <OnPlatform x:TypeArguments="View">
            <On Platform="iOS">
                <Label Text="iOS" />
            </On>
            <On Platform="Android">
                <Label Text="Android" />
            </On>
        </OnPlatform>
    </ContentView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM