Class Library Localization in Windows Universal / Store App

霸气de小男生 提交于 2019-12-03 20:54:18

In order to avoid writing a lot of boilerplate and error prone code when you add a new resource string like:

  1. Add it to .resw file
  2. Add it to your Static class that provides access to the resource
  3. Add it to each language specific .resw file (ex: en, fr, pt, etc)

You can use the following approach:

  1. Create "Strings" folder and add there just one folder for default language (for example "en-US") in your Class Library
  2. Add Resources.resw file to "en-US" folder with required keys/values
  3. Install Multilingual App Toolkit
  4. Enable MAT in VS for your Class Library (VS->Tools->Enable Multilingual App Toolkit)
  5. Add required languages to your Class Library (VS->Project->Add Translation languages...)
  6. Install ResW File Code Generator VS extension
  7. Go to Resources.resw file properties and set Custom Tool to "ReswFileCodeGenerator" (you can also specify namespace in Custom Tool Namespace)
  8. To solve issue with supported languages detection(currently generated manifest contains supported languages according to folder structure "Strings/en-US") you need to add folders for all required languages in your App library ("fr-FR", "bg-BG", etc) and put Resources.resw file with only one fake key.
  9. Build your solution and enjoy!

With this approach all your resources are available via static class generated by ReswFileCodeGenerator and all of them work with x:uid in XAML. You don't need to care about keys synchronization between different languages. Also MAT can translate your resources for you.

Ok, I found how to do this and with a sample project found here Basically the implementation is the following:

  • In the ClassLibrary create a folder named "Strings"
  • Inside the Strings folder create one for each language (ex: en, fr, pt, etc)
  • And add a Resources.resw in each of those folders with your keys/values

Now add a new Class in your ClassLibrary that has the following code(adapted to your project):

using System;
using Windows.ApplicationModel.Resources;

namespace MyClassLibraryName.Tools {
    public static class LocalizationTool {
        static ResourceLoader resourceLoader = null;

        public static string MyStringOne {
            get {
                String name;
                GetLibraryName("MyStringOne", out name);
                return name;
            }
        }

        private static void GetLibraryName(string resourceName, out string resourceValue) {
            if(resourceLoader == null) {
                resourceLoader = ResourceLoader.GetForCurrentView("MyClassLibraryName/Resources");
            }
            resourceValue = resourceLoader.GetString(resourceName);
        }
    }
}

And in your ClassLibrary or MainApp just call the following:

string text = LocalizationTool.MyStringOne;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!