Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MAUI; cannot access colors from resources in code

Tags:

maui

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>
like image 934
inno Avatar asked Feb 21 '26 07:02

inno


2 Answers

You can try the following code:

if (App.Current.Resources.TryGetValue("LiteGreen", out var colorvalue))
   var greencolor = (Color)colorvalue;
like image 143
Liyun Zhang - MSFT Avatar answered Feb 27 '26 08:02

Liyun Zhang - MSFT


I have started using this extension method that works really well:

public static T GetResource<T>(this ResourceDictionary dictionary, string key)
{
    if (dictionary.TryGetValue(key, out var value) && value is T resource)
        return resource;
    else
        return default;
}

The best part is this will work with all kinds of Resources, so you are free to use it however you like.

Usage:

Application.Current.Resource.GetResource<Color>("LiteGreen");
like image 32
FreakyAli Avatar answered Feb 27 '26 10:02

FreakyAli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!