using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; namespace DownKyi.Utils { public static class DictionaryResource { /// /// 从资源获取颜色的16进制字符串 /// /// /// public static string GetColor(string resourceKey) { //Color color = (Color)Application.Current.Resources[resourceKey]; //return color.ToString(); return Application.Current == null ? "#00000000" : ((Color)Application.Current.Resources[resourceKey]).ToString(); } /// /// 从资源获取字符串 /// /// /// public static string GetString(string resourceKey) { return Application.Current == null ? "" : (string)Application.Current.Resources[resourceKey]; } /// /// 根据languageCode切换界面语言 /// /// 语言-国家代码 public static void LoadLanguage(string languageCode) { LoadXamlDictionary(languageCode, "Languages"); } /// /// 切换主题 /// /// 主题 public static void LoadTheme(string theme) { LoadXamlDictionary(theme, "Themes"); } /// /// 更换xaml资源字典 /// /// xaml文件名,不包含扩展名 /// 文件所在包(路径) private static void LoadXamlDictionary(string fileName, string package) { if (string.IsNullOrEmpty(fileName) == false) { var dictionariesToRemove = new List(); foreach (var dictionary in Application.Current.Resources.MergedDictionaries) { if (dictionary.Source.ToString().Contains($"{package}")) { dictionariesToRemove.Add(dictionary); } } foreach (var item in dictionariesToRemove) { Application.Current.Resources.MergedDictionaries.Remove(item); } var languageDictionary = new ResourceDictionary() { Source = new Uri($"pack://application:,,,/DownKyi;component/{package}/{fileName}.xaml") }; Application.Current.Resources.MergedDictionaries.Add(languageDictionary); } } } }