Access Color inside Resources' Colors

Jassim Al Rahma 1,516 Reputation points
2023-03-14T18:58:59.2233333+00:00

Hi,

I am trying to access a Color inside the Resources->Colors.xaml but getting this error:

System.Collections.Generic.KeyNotFoundException: The resource 'ConnectedIconLight' is not present in the dictionary.
  at at Microsoft.Maui.Controls.ResourceDictionary.get_Item(String index)
  at DataEye.MainPage.CheckConnection() in /Users/jassim/Projects/DataEye/DataEye/MainPage.xaml.cs:133
  at DataEye.MainPage.<.ctor>b__10_0(Object s, EventArgs e) in /Users/jassim/Projects/DataEye/DataEye/MainPage.xaml.cs:28
  at at Microsoft.Maui.Dispatching.DispatcherTimer.OnTimerTick()
  at at ObjCRuntime.BlockStaticDispatchClass.TrampolineDispatchBlock(IntPtr block)
  at at UIKit.UIApplication.UIApplicationMain(Int32 argc, String[] argv, IntPtr principalClassName, IntPtr delegateClassName)
  at at UIKit.UIApplication.Main(String[] args, Type principalClass, Type delegateClass)
  at DataEye.Program.Main(String[] args) in /Users/jassim/Projects/DataEye/DataEye/Platforms/iOS/Program.cs:13

Here is my code:

LabelStatus.SetAppThemeColor(Label.TextColorProperty, App.Current.Resources["ConnectedIconLight"] as Color, Application.Current.Resources["ConnectedIconDark"] as Color);

and this the Color:

<Color x:Key="ConnectedIconLight">#000000</Color>

Kindly help..

Thanks,

Jassim

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,827 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 25,586 Reputation points Microsoft Vendor
    2023-03-15T06:21:34.9766667+00:00

    Hello,

    You can refer to the following code to access the Color you defined inside the Resources->Colors.xaml

                ResourceDictionary ColorResource = Application.Current.Resources.MergedDictionaries.FirstOrDefault() as ResourceDictionary;
                Color lightcolor = ColorResource["ConnectedIconLight"] as Color;
            Color darkcolor = ColorResource["ConnectedIconDark"] as Color;
            LabelStatus.SetAppThemeColor(Label.TextColorProperty, lightcolor, darkcolor);
    

    It's recommended that you use the StaticResource markup extension if you don't need to change the app theme at runtime.

    For more details, you can refer to
    Theme an app - .NET MAUI | Microsoft Learn
    Resource dictionaries - .NET MAUI | Microsoft Learn
    Consume XAML markup extensions - .NET MAUI | Microsoft Learn

    Best Regards,

    Wenyan Zhang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.