LanguageManager.cs 2.6 KB

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