LanguageManager.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. namespace MvvmScaffoldFrame48.Language
  8. {
  9. public static class LanguageManager
  10. {
  11. public static event EventHandler LanguageChangeEvent;
  12. private static int _nowLoadLanguage = 0;
  13. public static int NowLoadLanguage
  14. {
  15. get
  16. {
  17. return _nowLoadLanguage;
  18. }
  19. }
  20. public static List<string> LanguageList
  21. {
  22. get
  23. {
  24. return new List<string>()
  25. {
  26. "Chinese",
  27. "English"
  28. };
  29. }
  30. }
  31. public static void ChangeLanguage(string languageCode)
  32. {
  33. // 获取现有的非语言资源字典(如样式)
  34. var existingNonLanguageDictionaries = Application.Current.Resources.MergedDictionaries
  35. .Where(rd => !IsLanguageResourceDictionary(rd))
  36. .ToList();
  37. // 清除现有字典并重新添加
  38. Application.Current.Resources.MergedDictionaries.Clear();
  39. // 先添加语言资源字典
  40. var languageResourceDict = new ResourceDictionary();
  41. switch (languageCode)
  42. {
  43. case "Chinese":
  44. languageResourceDict.Source = new Uri("/Language/String_Chinese.xaml", UriKind.Relative);
  45. _nowLoadLanguage = 0;
  46. break;
  47. case "English":
  48. languageResourceDict.Source = new Uri("/Language/String_English.xaml", UriKind.Relative);
  49. _nowLoadLanguage = 1;
  50. break;
  51. }
  52. Application.Current.Resources.MergedDictionaries.Add(languageResourceDict);
  53. // 再添加其他非语言资源字典(如样式)
  54. foreach (var dict in existingNonLanguageDictionaries)
  55. {
  56. Application.Current.Resources.MergedDictionaries.Add(dict);
  57. }
  58. OnLanguageChangeEvent();
  59. }
  60. // 辅助方法:判断是否为语言资源字典
  61. private static bool IsLanguageResourceDictionary(ResourceDictionary resourceDict)
  62. {
  63. if (resourceDict.Source == null) return false;
  64. var sourcePath = resourceDict.Source.ToString().ToLower();
  65. return sourcePath.Contains("/language/string_") ||
  66. sourcePath.Contains("\\language\\string_");
  67. }
  68. private static void OnLanguageChangeEvent()
  69. {
  70. LanguageChangeEvent?.Invoke(null, EventArgs.Empty);
  71. }
  72. }
  73. }