question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Application.Current.Resources no keys available

See original GitHub issue

Description

Hello, everyone,

I tried to load a style from code, unfortunately the ResourceDictionary shows me that it has 35 objects but no single key or value.

I don’t know if I’m doing something wrong, but I can’t load a style with a key

image image image

Steps to Reproduce

  1. Create Maui App
  2. Add Button in MainPage
  3. Add code
    private void Button_Clicked(object sender, EventArgs e)
    {
		var res = Application.Current.Resources.MergedDictionaries.FirstOrDefault() as ResourceDictionary;

		if(res.ContainsKey("Primary"))
                {
        
                }
    }

Version with bug

6.0 (current)

Last version that worked well

Unknown/Other

Affected platforms

Android, I was not able test on other platforms

Affected platform versions

Android API 31

Did you find any workaround?

No response

Relevant log output

No response

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:7
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
StephaneDelcroixcommented, Oct 5, 2022

you can’t enumerate the resources (design choice at the time, for reasons I can’t recall at the moment), but you can query it using TryGetValue()

the main purpose of ResourceDictionary is to be the source for {StaticResource}

1reaction
breenbobcommented, Jul 6, 2022

From inspecting the resource dictionary a bit more closely, I could see that under the Private properties there is a property called MergedResources which looks to be populated appropriately: image

So as a workaround, I’ve written an extension method to find a resource from this. It’s not ideal, and not going to be very efficient as it uses reflection on every call to it, so I will be removing this workaround from my own code as soon as this issue is fixed in Maui, but at least it works.

public static object FindResource(this ResourceDictionary mainResourceDictionary, string resourceKey)
{
        var mergedResources = mainResourceDictionary
            .GetType()
            .GetProperty("MergedResources", BindingFlags.Instance | BindingFlags.NonPublic)
            .GetValue(mainResourceDictionary);

        var dict = ((IEnumerable<KeyValuePair<string, object>>)mergedResources)
            .ToDictionary(x => x.Key, y => y.Value);

        if (dict?.ContainsKey(resourceKey) == true)
        {
            return dict[resourceKey];
        }

        return null;
}

The reason for Casting to an IEnumerable<KeyValuePair<string, object>> is that casting to a Maui.Controls.ResourceDictionary throws an exception for some reason. The actual type of the underlying implementation property was an IEnumerable<KeyValuePair<string, object>>: image

Usage: myView.Style = Application.Current.Resources.FindResource("StyleKey") as Style;

Control now getting Style object: image

Disclaimer - I’ve only tried this on Windows, but Op has said it also affects Android. The Microsoft.Maui.Controls.ResourceDictionary class implements a bunch of other collection type interfaces, so would be cautious about whether other platforms store the data in different collection types.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Can't retrieve WPF application resource if there is only one
I've found few references to bug when Application.Resources don't load when StartupURI is not defined. WPF: Cannot find resource defined in ...
Read more >
Application.Resources Property (System.Windows)
Gets or sets a collection of application-scope resources, such as styles and brushes. ... Resources is thread safe and is available from any...
Read more >
How can I use an application resource ?
No resource with the key of 'GelButton' is found in the current page, so the resource lookup scope for the requested resource continues...
Read more >
Managing Application Resources when WPF is Hosted
The primary issue is that the runtime host is not WPF in these cases which means that Application.Current.Resources is not available.
Read more >
WPF Resource Key Collision - Software Development and more
Although a resource key must be unique within any individual dictionary, a key can exist multiple times in a set of merged dictionaries....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found