UWP 使用语言包

Fork Me On Github
zodream 编程技术 C# 2020年04月

UWP 使用语言包

我的程序默认语言为 zh-CN

则新建文件夹 Strings\zh-CN

再添加新建项 资源文件(.resw) 新建文件 Resources.resw

添加 xaml 控件的文字

例如要设置 TextBlockText

xml
 
<TextBlock Text="开"/>
1
  1. TextBlock 添加属性 x:Uid
xml
 
<TextBlock x:Uid="OnLabel"/>
1
  1. Resources.resw 添加一行
名称
OnLabel.Text

名称的组成为 {x:Uid}.{属性名}

如果要给一个控件设置多个属性

名称
OnLabel.Text
OnLabel.Content

注意:

  1. x:Uid 属性是没法在代码中获取到的

使用代码使用语言包

先添加在一个类上增加一个公开方法: 例如 类名 AppResource

c#
                              
#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
123456789101112131415161718192021222324252627282930

Resources.resw 添加一行

名称
appName 开始

使用

c#
 
var name = AppResource::GetString("appName");
1

注意:

  1. 使用 AppResource::GetString("OnLabel.Text")AppResource::GetString("OnLabel") 这种方式是不行,也就是 xaml 上使用的名称没法在代码中使用,只能多增加一条
  2. 名称 OnLabel.TextOnLabel 添加是冲突的

多语言

通过 vs 的扩展添加 Multilingual App Toolkit 能自动生成其他语言的翻译

参考

  1. Win10 UWP 开发系列:使用多语言工具包让应用支持多语言
点击查看全文
标签: uwp
0 313 0
uwp win2d 使用
2021年05月
win2d使用
UWP Custom Control自定义控件开发
uwp应用获取应用内的文件内容
UWP 上传图片
2020年04月
UWP 怎么上传图片