cfischy
cfischy

Reputation: 381

How to set platform-specific Style for a control in Maui?

My specific challenge is that the default Switch size on Android looks fine but is too large on iOS. I want to set the Scale property of all Switches on iOS to .8. I can do this for all platforms in Styles.xaml using...

<Style TargetType="Switch">
    <Setter Property="Scale" Value=".8:/>
</Style>

I can also easily set the Scale property for each Switch, one-by-one, in code-behind using conditional compilation as in...

#if #IOS
SwitchName1.Scale=.8;
SwitchName2.Scale=.8;
#endif

However, I'd prefer to set the global Style for all Switches to have a Scale of .8 on iOS-only. I'd even settle for having to set the Scale for Switches page by page. I tried to figure out how to set Scale=.8 for all Switches on a single page in code-behind and failed.

Any guidance would be greatly appreciated!

Upvotes: 4

Views: 4316

Answers (2)

Guangyu Bai - MSFT
Guangyu Bai - MSFT

Reputation: 4586

You can use the OnPlatform directly in the element you want to change. Here is the sample for the Scale of Switch.

<Switch Scale="{OnPlatform Android=.10, iOS=.8}" ></Switch>

The OnPlatform markup extension enables you to customize UI appearance on a per-platform basis. It provides the same functionality as the OnPlatform and On classes, but with a more concise representation.

More information about Customize UI appearance based on the platform and device idiom.

Upvotes: 2

ToolmakerSteve
ToolmakerSteve

Reputation: 21341

<OnPlatform> can't be applied to an entire <Style>, because OnPlatform can handle only one type at a time. Instead, use OnPlatform in each value of each property of the style:

<Style TargetType="Switch">
    <Setter Property="Scale" Value="{OnPlatform 1.0, iOS=0.8}"/>
</Style>

Alternatively, first declare a staticresource with type and key name:

<Application.Resources>
  <OnPlatform x:Key="MySwitchScale" x:TypeArguments="x:Double" Default="1.0">
    <On Platform="iOS" Value="0.8"/>
  </OnPlatform>

<Style TargetType="Switch">
    <Setter Property="Scale" Value="{x:StaticResource MySwitchScale}"/>
</Style>

Upvotes: 5

Related Questions