Search code examples
c#androidresourceswindows-phonexamarin.forms

Xamarin Forms - add color in global resources from code


I use this color in global resources(in app.xaml)

       <Color x:Key="MyColor" x:FactoryMethod="FromHex">
            <x:Arguments>
                <x:String>#ffffff</x:String>
            </x:Arguments>
        </Color>

I need different colors for Android and Windows Phone. I tried this code:

       <Color x:Key="MyColor" x:FactoryMethod="FromHex">
            <x:Arguments>
                <OnPlatform x:TypeArguments="x:String"
                              Android="#006ABB"
                              WindowsPhone="#ffffff"  />
                <x:String></x:String>
            </x:Arguments>
        </Color>

but it not work. Tell me - how to add it in code behind. Is it possible?


Solution

  • You can do it in App.xaml, no need to go to code. Simply you need a little bit different approach. Here is the code

    <Application.Resources>
        <ResourceDictionary>
          <OnPlatform
            x:Key="MyColor"
            x:TypeArguments="Color"
            Android="#006ABB"
            iOS="#006A00"
            WinPhone="#ffffff"/>
        </ResourceDictionary>
      </Application.Resources>
    

    The reason why this works, is because OnPlatform generic class has implicit conversation operator defined which can convert each OnPlatform object to its inbound generic T class. Something like this

    public static implicit operator T(OnPlatform<T> onPlatform)