本地化 WPF 应用程序不起作用?

Localising a WPF application doesn't work?

我一定是漏掉了什么。

我在 VS2015 中创建了一个全新的 WPF 应用程序。我创建了一个资源 'String1' 并将值设置为 'fksdlfdskfs'。

我更新默认 MainWindow.xaml.cs 以便构造函数具有:

    public MainWindow()
    {
        InitializeComponent();
        this.Title = Properties.Resources.String1;
    }

和 运行 应用程序,它工作正常,我的 window 标题是 fksdlfdskfs。

在 AssemblyInfo.cs 文件中,我看到以下注释:

//In order to begin building localizable applications, set 
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>.  For example, if you are using US english
//in your source files, set the <UICulture> to en-US.  Then uncomment
//the NeutralResourceLanguage attribute below.  Update the "en-US" in
//the line below to match the UICulture setting in the project file.

//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]

所以我将以下内容添加到我的 WpfApplication5.csproj 文件中并在 VS 中重新加载项目:

<UICulture>en-US</UICulture>

然后取消注释 AssemblyInfo.cs 中的以下行:

[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]

如果我现在转到 运行 应用程序,应用程序不再 运行s 并且我在读取资源的行中收到以下异常:

System.Resources.MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "WpfApplication5.Properties.Resources.en-US.resources" was correctly embedded or linked into assembly "WpfApplication5" at compile time, or that all the satellite assemblies required are loadable and fully signed.

如果我在 AssemblyInfo.cs 文件中将 UltimateResourceFallbackLocation.Satellite 更改为 UltimateResourceFallbackLocation.MainAssembly,则会出现以下异常:

System.IO.IOException: Cannot locate resource 'mainwindow.xaml'

我做错了什么或者我错过了什么?

您不会被迫使用代码隐藏进行本地化,您可以简单地使用 x:Static 标记扩展绑定到静态字段:

<Window
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:properties="clr-namespace:SandBox.Properties"
    Title="{x:Static properties:Resources.TitleSandbox}">

</Window>

只需确保您的资源文件访问修饰符设置为 Public

您收到的错误消息通常意味着您没有 Resource.en-US.resx 文件,因为 [assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] 在这里告诉您的应用程序使用 en-US 资源文件作为默认源。 如果您想快速消除错误,请添加名为 Resources.en-US.resx 的文件

我个人对 WPF 应用程序的本地化是:

  • 我保留 AssemblyInfo.cs 原样,这意味着 Resource.resx(没有语言 ID)文件将是默认文件(通常是 en-US)
  • 我在默认值旁边创建额外的 Resource.{id}.resx 文件,如下所示:

    它通常与 Resource.resx 相同,但翻译成匹配的语言

  • 我在启动时(通常在 App.xaml.cs 中)使用用户可设置的语言 ID 强制文化,以便用户可以更改应用程序语言:
// language is typically "en", "fr" and so on
var culture = new CultureInfo(language);
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
// You'll need to restart the app if you do this after application init