Set color value dynamically in App.xaml style

Issue

In my Xamarin Forms application I have multiple styles including colours.

App.xaml:

<prism:PrismApplication.Resources>
<ResourceDictionary>
<Color x:Key"primary_colour">#000a3d</Color>
...

Which I’m using on other .xaml pages:

<ContentPage Title"Menu" BackgroundColor"{StaticResource primary_colour}">

My question is, how can I change the colour value (#000a3d) in App.xaml dynamically (it will be different based on client logged in)? Can I bind that value from App.xaml.cs file?

Solution

use DynamicResource, from Xamarin documentaion it says:

The DynamicResource markup extension is similar to the StaticResource markup extension in that both use a dictionary key to fetch a value from a ResourceDictionary. However, while the StaticResource performs a single dictionary lookup, the DynamicResource maintains a link to the dictionary key. Therefore, if the dictionary entry associated with the key is replaced, the change is applied to the visual element. This enables runtime style changes to be made in an application.

Therefore your page will be:

<ContentPage Title"Menu" BackgroundColor"{DynamicResource primary_colour}">

and your code to change the colour would be:

Application.Current.Resources["primary_colour"]  Color.Green;

Answered By – User1

Leave a Comment