UWP 使用语言包
2020年4月16日 20:44
编程技术
UWP 使用语言包
我的程序默认语言为 zh-CN
则新建文件夹 Strings\zh-CN
再添加新建项 资源文件(.resw) 新建文件 Resources.resw
添加 xaml 控件的文字
例如要设置 TextBlock 的 Text 
<TextBlock Text="开"/>
- 给 
TextBlock添加属性x:Uid 
<TextBlock x:Uid="OnLabel"/>
- 在 
Resources.resw添加一行 
| 名称 | 值 | 
|---|---|
| OnLabel.Text | 开 | 
名称的组成为 {x:Uid}.{属性名}
如果要给一个控件设置多个属性
| 名称 | 值 | 
|---|---|
| OnLabel.Text | 开 | 
| OnLabel.Content | 开 | 
注意:
x:Uid属性是没法在代码中获取到的
使用代码使用语言包
先添加在一个类上增加一个公开方法: 例如 类名 AppResource
#region 语言包获取文字
        private static ResourceLoader CurrentResourceLoader
        {
            get { return _loader ?? (_loader = ResourceLoader.GetForCurrentView("Resources")); }
        }
        private static ResourceLoader _loader;
        private static readonly Dictionary<string, string> ResourceCache = new Dictionary<string, string>();
        /// <summary>
        /// 获取资源字典的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetString(string key)
        {
            if (ResourceCache.TryGetValue(key, out string s))
            {
                return s;
            }
            else
            {
                s = CurrentResourceLoader.GetString(key);
                ResourceCache[key] = s;
                return s;
            }
        }
 #endregion
在 Resources.resw 添加一行  
| 名称 | 值 | 
|---|---|
| appName | 开始 | 
使用
var name = AppResource::GetString("appName");
注意:
- 使用 
AppResource::GetString("OnLabel.Text")或AppResource::GetString("OnLabel")这种方式是不行,也就是xaml上使用的名称没法在代码中使用,只能多增加一条 - 名称 
OnLabel.Text和OnLabel添加是冲突的 
多语言
通过 vs 的扩展添加 Multilingual App Toolkit 能自动生成其他语言的翻译