Search code examples
xamarinxamarin.formsxamarin.androidxamarin.iosxamarin-studio

How to apply condition inside the theme resource dictionary in Xamarin forms


I had applied light theme and dark theme for Xamarin app via resource dictionary.

here is my resource samples

Light theme:

<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    x:Class="App.Views.Themes.LightTheme"
                    xmlns:converters="clr-namespace:App.Services.Helper;assembly=App.Services">

 <!-- bootm bar background color -->
    <Color x:Key="BottomBar">#17a7a7</Color>

</ResourceDictionary>

Dark Theme :

<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    x:Class="App.Views.Themes.DarkTheme"
                    xmlns:converters="clr-namespace:App.Services.Helper;assembly=App.Services">

  <!-- bootm bar background color -->
    <Color x:Key="BottomBar">#292a2a</Color>

</ResourceDictionary>

Both themes are working fine , But i need to change only the bottom bar color according the user level.Its only for the light theme.

The condition is:

if(memeberlevel =="Basic"){
  //need to change bottom bar color as green
}
else if(memeberlevel =="Intermediate")
{
   //need to change bottom bar color as silver
}
else
{
  //need to change bottom bar color as gold
}

How i apply this condition inside the Light theme resource dictionary for

 <Color x:Key="BottomBar">#17a7a7</Color>

Here i need to set green, silver and gold for x:Key="BottomBar" according to user level

Appreciate a quick help. Thanks in advance


Solution

  • You can do it in your code, not in resource dictionary by conditionally binding color to your viewmodel. Example how to access resource color:

    (Color)Application.Current.Resources["BottomBar"]
    

    You can define several colors that will reflect remember level in your resource dictionary. If you need it only for dark theme then define them as different colors in dark theme resource dictionary and leave them the same in light theme.