Home > Back-end >  How to dynamically change the values of MAUI OnPlatform resources?
How to dynamically change the values of MAUI OnPlatform resources?

Time:10-11

I understood how to change Color below in C#.

<Color x:Key="TextColor">Yellow</Color>

Resources["TextColor"] = Colors.Blue;

But I don't know how to change, for example Android's value below in C#.

<OnPlatform x:Key="FontSize" x:TypeArguments="x:Double">
    <On Platform="Android" Value="20"/>
    <On Platform="WinUI" Value="80"/>
</OnPlatform> 

CodePudding user response:

So what you need to do is reassign the value to the Resource.

So below:

<OnPlatform x:Key="FontSize" x:TypeArguments="x:Double">
<On Platform="Android" Value="20"/>
<On Platform="WinUI" Value="80"/>
</OnPlatform> 

Can be updated like:

 Resources["FontSize"] = GetFontSize();

   private int GetFontSize()
   {
    if (Microsoft.Maui.Devices.DeviceInfo.Platform == DevicePlatform.Android)
    {
        return 20;
    }
    else if (Microsoft.Maui.Devices.DeviceInfo.Platform == DevicePlatform.WinUI)
    {
        return 20;
    }
    else
    {
        return 80;
    }
  }
 

Hope this helps!

CodePudding user response:

I wrote a demo for you and it worked well. You can refer to this.

<Button Margin="0,10,0,0"  Text="Learn more"
        Command="{Binding OpenWebCommand}"
        TextColor="White">
    <Button.BackgroundColor>
        <OnPlatform x:TypeArguments="Color">
            <On Platform="Android" Value="Green"/>
            <On Platform="iOS" Value="Orange"/>
            <On Platform="UWP" Value="Purple"/>
        </OnPlatform>
    </Button.BackgroundColor>
</Button>

For more information, you can read this website.

  • Related