本地化WPF应用程序无法正常工作?

5

我在这里可能漏掉了什么。

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

我更新了默认的MainWindow.xaml.cs,使构造函数包含:

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

运行应用程序,发现它能很好地运作,我的窗口标题是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)]

如果我现在运行这个应用程序,它将不再运行,并且我会在读取资源的那一行得到以下异常:

System.Resources.MissingManifestResourceException: 找不到适用于指定区域性或中性区域性的任何资源。请确保“WpfApplication5.Properties.Resources.en-US.resources”在编译时已经正确地嵌入或链接到程序集“WpfApplication5”中,或者需要加载并完全签名的所有卫星程序集都可用。

如果我在AssemblyInfo.cs文件中将UltimateResourceFallbackLocation.Satellite更改为UltimateResourceFallbackLocation.MainAssembly,我将得到以下异常:

System.IO.IOException: 无法找到资源'mainwindow.xaml'

我做错了什么或者我缺少了什么?
1个回答

6

您不必强制使用代码后端进行本地化,您可以简单地使用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>

请确保您的资源文件访问修饰符设置为公共

屏幕资源文件

您通常收到的错误消息意味着您没有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

1
这是最简单和基本的方法,但最大的缺点是应用程序需要重新启动。还有一些其他替代方法来解决这个问题,但在这些方式中,您的界面字符串在开发窗口中不可见(因为它们是动态的)。我认为有一个叫做wpflocalizationextension的库可以让事情变得更容易。 - mcy
1
好的,非常感谢您的指导。接下来的问题是,是否可以在Visual Studio之外创建/编辑每种语言的资源,还是需要像这样编译每种语言?当我们有20多种语言时,而且每个国家以不同的时间发送它们的翻译时,我觉得这会变得很麻烦! - GoldieLocks
@Uwy 使用 Microsoft MAT:https://developer.microsoft.com/zh-cn/windows/develop/multilingual-app-toolkit - juFo
1
你仍然可以使用多个resx文件,但是通过使用MAT,您可以使用xlf文件(国际翻译标准)。这也可以让您更好地管理翻译。试试看吧,你会发现它很不错的;-) - juFo
谢谢!我会在处理小项目时尝试一下。 - Uwy
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接