Search code examples
maui

MAUI; cannot access colors from resources in code


I am trying to access colors from my colors file (under styles) in my maui application:

<Color x:Key="LiteGreen">#7DD2CD</Color>
    <Color x:Key="VeryLiteGreen">#a4dbda</Color>
    <Color x:Key="LiteBlue">#c3e1ed</Color>

If I wanna access the colors in xaml, this is how I did it and what worked for me:

BorderColor="{StaticResource LiteGreen}"

Now I tried to access the same color in code:

var color = this.Resources["LiteGreen"] as Color;

Which failes with "LiteGreen is not inside the resource dict"

enter image description here

I tried many different variations but to no avail.

EDIT:

my app.xaml (basic).

<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Skillbased"
             x:Class="Skillbased.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
                <ResourceDictionary Source="Resources/Styles/Styles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Solution

  • You can try the following code:

    if (App.Current.Resources.TryGetValue("LiteGreen", out var colorvalue))
       var greencolor = (Color)colorvalue;