Search code examples
xamlxamarin.forms

How to access resource located in merged dictionary from code


I have a bunch of Colors inside a couple of ResourceDicitonaries like this:

<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    xmlns:s="clr-namespace:System;assembly=netstandard">

    <Color x:Key="Color.Background">#301536</Color>
</ResourceDictionary>

And I simply add both to the App.xaml like so:

<!--Colors-->
<ResourceDictionary Source="Resources/Colors/Light.xaml"/>
<ResourceDictionary Source="Resources/Colors/Dark.xaml"/>

The ResourceDicitonary file is simply a .xaml file without any bundled .cs, and both of the two dictionaries are set on the App.xaml without having to define them inside a MergedDicionaries group.

When trying to access the a Color from the code, I'm not able to find it, looks like it was not added to the resource list.

var color = Application.Current.Resources.FirstOrDefault(f => f.Key == "Color.Background")
    .Value as Color? ?? Color.Crimson;

Is there any way to access a resource like FindResource/TryFindResource available in WPF?


I also tried to access/see the contents of the MergedDictionaries but for some reason the merged dictionaries are always empty.


Solution

  • Thanks to another person I was able to construct this working code:

    internal static Color TryGetColor(string key, Color fallback)
    {
        Application.Current.Resources.TryGetValue(key, out var color);
    
        return color as Color ?? fallback;
    }