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

Gol*_*cks 5 .net c# globalization wpf xaml

我一定在这里想念什么。

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

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

    public MainWindow()
    {
        InitializeComponent();
        this.Title = Properties.Resources.String1;
    }
Run Code Online (Sandbox Code Playgroud)

并运行该应用程序,它运行正常,我的窗口标题是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)]
Run Code Online (Sandbox Code Playgroud)

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

<UICulture>en-US</UICulture>

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

[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
Run Code Online (Sandbox Code Playgroud)

如果现在去运行该应用程序,该应用程序将不再运行,并且在读取资源的那一行上会出现以下异常:

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

如果我在AssemblyInfo.cs文件中更改UltimateResourceFallbackLocation.SatelliteUltimateResourceFallbackLocation.MainAssembly,则会得到以下异常:

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

我做错了什么或我想念什么?

Uwy*_*Uwy 5

您不必使用隐藏代码进行本地化,您可以简单地使用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>
Run Code Online (Sandbox Code Playgroud)

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

屏幕资源文件

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

我个人为本地化 WPF 应用程序所做的是:

  • 我保持AssemblyInfo.cs原样,这意味着Resource.resx(没有语言 ID)文件将是默认文件(通常是美国)
  • 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
Run Code Online (Sandbox Code Playgroud)