Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically access a resource string from App.xaml?

I have some Strings I want to access from my code in App.xaml like:

<Application.Resources>
    <ai:TelemetryContext x:Key="ApplicationInsightsBootstrapper" xmlns:ai="using:Microsoft.ApplicationInsights"/>
    <ResourceDictionary x:Key="rd">
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="GlobalStylesResourceDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <!-- Application-specific resources. -->
        <x:String x:Key="AppName">Platypus</x:String>
        <x:String x:Key="BingMapsNamespace">http://schemas.microsoft.com/search/local/ws/rest/v1</x:String>
    </ResourceDictionary>
</Application.Resources>

And I want to programmatically get those values, so I wrote this utility function:

internal static String GetResourceString(String keyStr)
{
    var resldr = new Windows.ApplicationModel.Resources.ResourceLoader();
    return resldr.GetString(keyStr);
}

But if fails with, "A first chance exception of type 'System.Exception' occurred in Platypus.exe WinRT information: ResourceMap Not Found."

I thought I found the solution to the problem here, where it is said that way of doing it is deprecated, and I should do this instead:

internal static String GetResourceString(String keyStr)
{
    try
    {
        //var resldr = new Windows.ApplicationModel.Resources.ResourceLoader();
        //return resldr.GetString(keyStr);
        var resldr = ResourceLoader.GetForCurrentView();
        return resldr.GetString(keyStr);
    }
    catch (Exception ex)
    {
        Debug.WriteLine("Something wrong with the keyStr? Exception in GetResourceString(): {0}", ex.Message); 
    }
    return String.Empty;
}

But that doesn't work, either; I get the same old "WinRT information: ResourceMap Not Found." with this code, too.

The arg I'm passing is valid:

String bmn = GetResourceString("BingMapsNamespace");

So what's the dealio?

UPDATE

It may be just as well (or better, actually, as it will presumably work), to use App.xaml.cs rather than its angly cousin:

public static string BingMapsNamespace { get; set; }
. . .
BingMapsNamespace = "http://schemas.microsoft.com/search/local/ws/rest/v1";

And then access it from elsewhere like so:

String bmn = App.BingMapsNamespace;

Later: And yes, it does work. I'm marking the other as correct, as it obviously works for some people.

like image 321
B. Clay Shannon-B. Crow Raven Avatar asked Oct 25 '14 00:10

B. Clay Shannon-B. Crow Raven


1 Answers

This works fine for me:

<Application.Resources>
    <x:String x:Key="AppName">My App Name</x:String>
</Application.Resources>

Then in code:

string text = (string)App.Current.Resources["AppName"];

I don't know if that's the right way to do it, but it's convenient enough. :)

like image 72
Peter Duniho Avatar answered Nov 07 '22 18:11

Peter Duniho