Xamarin.Forms setting specific style for platform

2.8k Views Asked by At

I'm trying to style my UWP application with some specific styles, while on other platforms it should remain default.

This is my project layout:

enter image description here

I tried the following things: In Clients.Shared creating a style as following:

<Style x:Key="SomeStyle" TargetType="Button" />

And adding the same Style key in the Clients.Themes.UWP so it could hopefully override it, but no luck.

Then I tried Having a Dummy Style and using the onPlatform but that didn't work either, but I still think this is the way to go. I had the following code:

<Style x:Key="DummyStyle" TargetType="Button">
    <Setter Property="Style">
        <Setter.Value>
            <OnPlatform x:Key="ButtonStyle" x:TypeArguments="Style">
                <On Platform="UWP" Value="{StaticResource SomeStyle}"></On>
            </OnPlatform>
        </Setter.Value>
    </Setter>
</Style>

I tried messing around with merged ResourceDictionary.MergedDictionaries but there I couldn't include the xaml

Anybody have any clue?

3

There are 3 best solutions below

1
Andrew Shkolik On

Why do not use

<Button.Style>
    <OnPlatform x:TypeArguments="x:Style">
        <OnPlatform.iOS>...</OnPlatform.iOS>
        <OnPlatform.Android>...</OnPlatform.Android>
        <OnPlatform.WinPhone>...</OnPlatform.WinPhone>
    </OnPlatform>
</Button.Style>

Hope it will help.

3
Wilson Vargas On

Try this:

<OnPlatform x:TypeArguments="Color" Android="Green" iOS="White" WinPhone="White"
        x:Key="PrimaryColor" />


<Style x:Key="ButtonColor" TargetType="Button">
    <Setter Property="BackgroundColor" Value="{StaticResource PrimaryColor}" />
</Style>

<Button Text="Hello" HorizontalOptions="StartAndExpand"
   Grid.Row="2" Grid.ColumnSpan="2" Style="{StaticResource ButtonColor}" />

In this example, I am defining a style for a Button called ButtonColor. This Button will use a BackgroundColor of white for all platforms except Android where it will be Green.

I find this is the most common use for this tag with regard to styling; if you are working with fonts, be sure to run on simulator and actual devices to get the font that you want.

0
Christopher Stephan On

This syntax works for me:

<Style x:Key="zoneLabelStyle" TargetType="Label">
  <Setter Property="HeightRequest" Value="18" />
  <Setter Property="Margin">
    <OnPlatform x:TypeArguments="Thickness">
      <On Platform="Android" Value="0, -3, 0, 0" />
    </OnPlatform>
  </Setter>
</Style>