背景描述

最近接到一个需求,就是要求我们的 wpf 客户端具备本地化功能,实现中英文多语言界面。刚开始接到这个需求,其实我内心是拒绝的的,但是没办法,需求是永无止境的。所以只能想办法解决这个问题。

首先有必要说一下我们的系统架构。我们的系统是基于 prism 来进行设计的,所以每个业务模块之间都是相互独立,互不影响的 dll,然后通过主 shell 来进行目录的动态扫描来实现动态加载。

为了保证在不影响系统现有功能稳定性的前提下,如何让所有模块支持多语言成为了一个亟待解决的问题。

刚开始,我 google 了一下,查阅了一些资料,很多都是介绍如何在单体程序中实现多语言,但是在模块化架构中,我个人觉得这样做并不合适。做过本地化的朋友应该都知道,在进行本地化翻译的时候,都需要创建对应语言的资源文件,无论是使用 .xaml .resx.xml,这里面会存放我们的本地化资源。对于单体系统而言,这些资源直接放到主程序下即可,方便快捷。但是对于模块化架构的程序,这样做就不太好,而是应该将这些资源都分别放到自己模块内部由自己来维护,主程序只需规定整个系统的区域语言即可。

设计思路

面对上面的背景描述,我们可以大致描述一下我们期望的解决方式,主程序只负责对整个系统进行区域语言设置,每个模块的本地化由本模块内部完成,所有模块的本地化切换方式保持一致,依赖于共有的一种实现。如下图所示:

实现方案

由于如何使用 prism 不是本文的重点,所以这里就略过主程序和模块程序中相关的模板代码,感兴趣的小伙伴可以自行在园子里搜索相关技术文章。

参照上述的思路,我们可以做一个小示例来展示一下如何进行多模块多语言的本地化实践。

在这个示例中,我以 dotnetcore 3.0 版本的 wpf 和 prism 进行示例说明。在我们的示例工程中创建三个项目

  • blackapp
    • 引用 prism.unity 包
    • wpf app(.net core 版本),作为启动程序
  • blackapp.modulea
    • 引用 prism.wpf 包
    • wpf usecontrol(.net core 版本),作为示例模块
  • blackapp.common
    • classlibrary(.net core 版本),作为基础的公共服务层

blackapp.modulea 添加对 blackapp.common 的引用,并将 blackapp 和 blackapp.modulea 的项目输出修改为相同的输出目录。然后修改对应的基础代码,以确保主程序能正常加载并显示 modulea 模块及其内容。

上述操作完成后,我们就可以编写我们的测试代码了。按照我们的设计思路,我需要先在 blackapp.modulea 定义我们的本地化资源文件,对于这个资源文件的类型选择,理论上我们是可以选择任何一种基于 xml 的文件,但是不同类型的文件对于后面是否是埋坑行为这个需要认真考虑一下。这里我建议使用 xaml 格式的文件。我们在 blackapp.modulea 项目的根目录下创建一个 strings 的文件夹,然后里面分别创建 en-us.xamlzh-cn.xaml 文件。这里建议最好以语言名称作为文件名称,这样方便到时候查找。文件内容如下所示:

  • en-us.xaml
<resourcedictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:blackapp.modulea.strings"
    xmlns:system="clr-namespace:system;assembly=system.runtime">
    <system:string x:key="string1">hello world</system:string>
</resourcedictionary>
  • zh-cn.xaml
<resourcedictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:blackapp.modulea.strings"
    xmlns:system="clr-namespace:system;assembly=system.runtime">
    <system:string x:key="string1">世界你好</system:string>
</resourcedictionary>

资源文件定义好了,接下来就是如何使用了。

对于我们需要进行本地化的 xaml 页面,首先我们需要指当前使用到的资源文件,这个时候就需要在我们的 blackapp.common 项目中定义一个依赖属性了,然后通过依赖属性的方式来进行设置。由于语言种类有很多,所以我们定义一个文件夹目录的依赖属性,来指定当前页面需要用到的资源的文件夹路径,然后由辅助类到时候依据具体的语言类型来到指定目录查找指当的资源文件。
示例代码如下所示:

[runtimenameproperty(nameof(extranslationmanager))]
public class extranslationmanager : dependencyobject
{
    public static string getresourcedictionary(dependencyobject obj)
    {
        return (string)obj.getvalue(resourcedictionaryproperty);
    }

    public static void setresourcedictionary(dependencyobject obj, string value)
    {
        obj.setvalue(resourcedictionaryproperty, value);
    }

    // using a dependencyproperty as the backing store for resourcedictionary.  this enables animation, styling, binding, etc...
    public static readonly dependencyproperty resourcedictionaryproperty =
        dependencyproperty.registerattached("resourcedictionary", typeof(string), typeof(extranslationmanager), new propertymetadata(null));

}

本地化资源指定完毕后,我们就可以使用里面资源文件进行本地化操作。如果想在 xaml 对相应属性进行 标签式 访问,需要定义一个继承自 markupextension 类的自定义类,并在该类中实现 providevalue 方法。接下来在我们的 blackapp.common 项目中定义该类,示例代码如下所示:

[runtimenameproperty(nameof(extranslation))]
public class extranslation : markupextension
{
    public string stringname { get; private set; }
    public extranslation(string stringname)
    {
        this.stringname = stringname;
    }

    public override object providevalue(iserviceprovider serviceprovider)
    {
        object targetobject = (serviceprovider as iprovidevaluetarget)?.targetobject;

        resourcedictionary dictionary = getresourcedictionary(targetobject);
        if (dictionary == null)
        {
            object rootobject = (serviceprovider as irootobjectprovider)?.rootobject;
            dictionary = getresourcedictionary(rootobject);
        }

        if (dictionary == null)
        {
            if (targetobject is frameworkelement frameworkelement)
            {
                dictionary = getresourcedictionary(frameworkelement.templatedparent);
            }
        }

        return dictionary != null && stringname != null && dictionary.contains(stringname) ?
            dictionary[stringname] : stringname;
    }

    private resourcedictionary getresourcedictionary(object target)
    {
        if (target is dependencyobject dependencyobject)
        {
            object localvalue = dependencyobject.readlocalvalue(extranslationmanager.resourcedictionaryproperty);
            if (localvalue != dependencyproperty.unsetvalue)
            {
                var local = localvalue.tostring();
                var (basename,stringname) = splitname(local);
                var str = $"pack://application:,,,/{basename};component/{stringname}/{thread.currentthread.currentculture}.xaml";
                var dict = new resourcedictionary { source = new uri(str) };
                return dict;
            }
        }
        return null;
    }

    public static (string basename, string stringname) splitname(string name)
    {
        int idx = name.lastindexof('.');
        return (name.substring(0, idx), name.substring(idx + 1));
    }
}

此外,如果我们的 viewmodel 中也有数据需要进行本地化操作的化,我们可以定义一个扩展方法,示例代码如下所示:

public static class extranslationstring
{
    public static string gettranslationstring(this string key, string resourcedictionary)
    {
        var (basename, stringname) = extranslation.splitname(resourcedictionary);
        var str = $"pack://application:,,,/{basename};component/{stringname}/{thread.currentthread.currentculture}.xaml";
        var dictionary = new resourcedictionary { source = new uri(str) };
        return dictionary != null && !string.isnullorwhitespace(key) && dictionary.contains(key) ? (string)dictionary[key] : key;
    }
}

通过在 blackapp.common 中定义上述 3 个辅助类,基本可以满足我们的需求,我们可以却换到 blackapp.modulea 项目中,并进行如下示例修改

  • view 层使用示例
<usercontrol
    x:class="blackapp.modulea.views.mainview"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:ex="clr-namespace:blackapp.common;assembly=blackapp.common"
    xmlns:local="clr-namespace:blackapp.modulea.views"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:prism="http://prismlibrary.com/"
    d:designheight="300"
    d:designwidth="300"
    ex:extranslationmanager.resourcedictionary="blackapp.modulea.strings"
    prism:viewmodellocator.autowireviewmodel="true"
    mc:ignorable="d">
    <grid>
        <stackpanel horizontalalignment="center" verticalalignment="center">
            <textblock text="{binding message}" />
            <textblock text="{ex:extranslation string1}" />
        </stackpanel>
    </grid>
</usercontrol>
  • viewmodel 层使用示例
"message".gettranslationstring("blackapp.modulea.strings")

最后,我们就可以在我们的 blackapp 项目中的 app.cs 构造函数中来设置我们程序的语言类型,示例代码如下所示:

public partial class app
{
    public app()
    {
        //cultureinfo ci = new cultureinfo("zh-cn");
        cultureinfo ci = new cultureinfo("en-us");
        thread.currentthread.currentculture = ci;
    }
    protected override window createshell()
    {
        return container.resolve<mainwindow>();
    }

    protected override void registertypes(icontainerregistry containerregistry)
    {

    }

    protected override imodulecatalog createmodulecatalog()
    {
        return new directorymodulecatalog() { modulepath = appdomain.currentdomain.basedirectory };
    }
}

写到这里,我们应该就可以进行本地化的测试工作了,尝试编译运行我们的示例程序,如果不出意外的话,应该是可以通过在 主程序中设置区域类型来更改模块程序中的对应本地化资源内容。

最后,整个示例项目的组织结构如下图所示:

总结

对于模块化架构的本地化实现,有很多的实现方式,我这里介绍的只是一种符合我们的业务场景的一种实现,期待大佬们在评论区留言提供更好的解决方案。

参考

  • localization of a wpf app – the simple approach
  • wpf-localization-multiple-resource-resx-one-language
  • localizemarkupextension
  • markup extensions and wpf xaml