2017-07-27 103 views
3

我必須在這裏失去一些東西。本地化WPF應用程序不起作用?

我在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.SatelliteUltimateResourceFallbackLocation.MainAssembly,我得到下面的異常,而不是:

System.IO.IOException:無法找到資源 'mainwindow.xaml'

我在做什麼錯,或者我錯過了什麼?

回答

3

你不會被迫使用後面的代碼進行本地化,您可以簡單地使用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> 

只要確保你的資源文件的訪問修飾符設置爲公共

Screen resource file

你通常該錯誤消息意味着你沒有Resource.en-US.resx文件,因爲[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]是在這裏告訴您的應用程序使用EN EN-US資源文件作爲默認源。 添加,如果你想擺脫錯誤的快捷方式

名爲 Resources.en-US.resx文件

我親自做本地化一個WPF應用程序是:

  • 我離開AssemblyInfo.cs,因爲它是,這意味着Resource.resx (無語言標識)的文件將默認值(一般爲EN-US)
  • 我創造更多的Resource.{id}.resx文件旁邊,默認是這樣的: sample

    它通常是與用戶可設置的語言ID相同Resource.resx但在匹配的語言

  • 我迫使培養在啓動時(通常在App.xaml.cs)平移,使得用戶可以改變應用程序語言:
// 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

+0

當然!我自己使用ResXResourceManager(https://github.com/tom-englert/ResXResourceManager),因爲它在Visual Studio中提供了更好的版本功能(例如列出一個表中的所有文件和所有語言)。還有一個專門的客戶端來編輯沒有VS的resx文件,你也可以導出/導入excel文件 – Uwy