Home > C#, WinRT > A simple approach to access localized resources in Windows Store apps

A simple approach to access localized resources in Windows Store apps

09/02/2013

To simplify the use of ResourceLoader in my apps, I have came to the following solution. Suppose we have a project with two Resource files:

Resource files in Solution Explorer

Resource files in Solution Explorer

In each of them, three resources are defined, for example (in the English resource file):

Localization Resources

Localization Resources

Now, add the following class to our project:

using System;
using Windows.ApplicationModel.Resources;

namespace LocalizationTest
{
    public enum LocalizedStringEnum
    {
        FirstName,
        LastName,
        Mail
    }

    public static class LocalizedStrings
    {
        private static ResourceLoader resourceLoader;

        static LocalizedStrings()
        {
            resourceLoader = new ResourceLoader();
        }

        public static string GetString(LocalizedStringEnum resource)
        {
            return resourceLoader.GetString(resource.ToString());
        }
    }
}

Note, in particular, the enum LocalizedString, that contains an element for each localizable resource, with the same name that we have used in the Resource file. The LocalizedStrings static class provides access to ResourceLoader and allows to use an enum value to specify the resource we want to retrieve. So, if for example we want to get the localize string for Mail, we must write:

var mailText = LocalizedStrings.GetString(LocalizedString.Mail);

Following this approach, every time we add a new resource, we need only to add the corresponding value in the enum, using the same name of the resource itself.

It’s a little tip, but I think it could be useful to share it.

Categories: C#, WinRT
%d bloggers like this: