為所欲為,嗯
話不多說,先看效果吧(事先說明,我的方法不是最好的,但是我用着最有效。)
【吐槽一下博客園上傳的圖片,我的App敲雞漂亮滴,自帶亞克力效果,怎么圖片上傳上來這么多的噪點啊。】
【 商店地址傳送門:https://www.microsoft.com/store/apps/9n19jm5g8mz4】
按我的方法做有一個缺點:不能立馬顯示新的語言,需要重啟App。網上別人也是這樣的。
===============================================================================
其實很簡單
① 給每一個控件設置 x:Uid
比如一個Textbox x:Uid=“textbox_language”
然后我們在解決方案里面找到“Strings”文件夾,打開“en-us”文件夾,添加一行textbox_language.Text,它的值是“Language”。
在Strings下面新建"zh-cn"文件夾,添加一行textbox_language.Text,它的值是“語言”。
更多的語言代碼請參考 https://msdn.microsoft.com/en-us/library/ms533052(v=vs.85).aspx
② 本地存儲一下所選擇的語言
切換語言總得有個下拉框來承載這些語言吧,建議顯示的格式為 “代碼 語言名稱”,中間有個空格的。這樣有好處,一會你就知道了。
private void comboBoxLanguage_SelectionChanged(object sender, SelectionChangedEventArgs e) { string temp = comboBoxLanguage.SelectedItem.ToString(); string[] tempArr = temp.Split(' '); ApplicationData.Current.LocalSettings.Values["CurrentLanguage"] = tempArr[0]; }
③ 在App.cs中讀取
大體意思就是本都有這個CurrentLanguage設置,就讀取出來。當然會存在Auto的情況,那么需要一個類獲取當前系統的語言。如果不存在設置,之前我默認是英文了,現在也改成Auto那樣。
if (ApplicationData.Current.LocalSettings.Values["CurrentLanguage"] != null) { strCurrentLanguage = ApplicationData.Current.LocalSettings.Values["CurrentLanguage"].ToString(); if (strCurrentLanguage == "auto") { ApplicationLanguages.PrimaryLanguageOverride = LanguageHelper.GetCurLanguage(); } else ApplicationLanguages.PrimaryLanguageOverride = strCurrentLanguage; } else { ApplicationLanguages.PrimaryLanguageOverride = strCurrentLanguage = LanguageHelper.GetCurLanguage(); //ApplicationLanguages.PrimaryLanguageOverride = strCurrentLanguage = "en-us"; }
InitializeComponent();
④ LanguageHelper類寫的一般,就是剛才提到的
public static string GetCurLanguage() { var languages = GlobalizationPreferences.Languages; if (languages.Count > 0) { List<string> lLang = new List<string>(); lLang.Add("zh-cn、zh、zh-Hans、zh-hans-cn、zh-sg、zh-hans-sg"); lLang.Add("zh-hk、zh-Hant、zh-mo、zh-tw、zh-hant-hk、zh-hant-mo、zh-hant-tw"); lLang.Add("de、de-at、de-ch、de-de、de-lu、de-li"); lLang.Add("en-us、en、en-au、en-ca、en-gb、en-ie、en-in、en-nz、en-sg、en-za、en-bz、en-hk、en-id、en-jm、en-kz、en-mt、en-my、en-ph、en-pk、en-tt、en-vn、en-zw、en-053、en-021、en-029、en-011、en-018、en-014"); lLang.Add("es、es-cl、es-co、es-es、es-mx、es-ar、es-bo、es-cr、es-do、es-ec、es-gt、es-hn、es-ni、es-pa、es-pe、es-pr、es-py、es-sv、es-us、es-uy、es-ve、es-019、es-419"); lLang.Add("fr、fr-be、fr-ca、fr-ch、fr-fr、fr-lu、fr-015、fr-cd、fr-ci、fr-cm、fr-ht、fr-ma、fr-mc、fr-ml、fr-re、frc-latn、frp-latn、fr-155、fr-029、fr-021、fr-011"); lLang.Add("hi、hi-in"); lLang.Add("it、it-it、it-ch"); lLang.Add("ja、ja-jp"); lLang.Add("pt、pt-pt、pt-br"); lLang.Add("ru、ru-ru"); for (int i = 0; i < lLang.Count; i++) { if (lLang[i].ToLower().Contains(languages[0].ToLower())) { string temp = lLang[i].ToLower(); string[] tempArr = temp.Split('、'); return tempArr[0]; } else return "en-us"; } } return "en-us"; }
如你所見,我之前叫你存儲那個代碼,在這里就可以比對。當然lLang里面的語言code也必須是標准的。
⑤ 善后工作
上面基本上也就完成了多語言了。
但是你需要在進入設置前,讀取並設置combobox 的值,這樣才算完整的。代碼就不貼了。