我有下面的命令绑定到我的按钮,它应该检测当前使用的主题并改变它(黑暗或光明)。
var existingResourceDictionary = Application.Current.Resources.MergedDictionaries
.Where(rd => rd.Source != null)
.SingleOrDefault(rd => Regex.Match(rd.Source.OriginalString, @"(\/MaterialDesignThemes.Wpf;component\/Themes\/MaterialDesignTheme\.)((Light)|(Dark))").Success);
if (existingResourceDictionary == null)
throw new ApplicationException("Unable to find Light/Dark base theme in Application resources.");
if (existingResourceDictionary.Source.ToString().Contains("Light"))
{
Settings.Default.Theme = true;
Settings.Default.Save();
}
else
{
Settings.Default.Theme = false;
Settings.Default.Save();
}
var source =
$"pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.{(Settings.Default.Theme ? "Dark" : "Light")}.xaml";
var newResourceDictionary = new ResourceDictionary() { Source = new Uri(source) };
Application.Current.Resources.MergedDictionaries.Remove(existingResourceDictionary);
Application.Current.Resources.MergedDictionaries.Add(newResourceDictionary);在ViewModel中(当我运行应用程序时),它应该检测上面的按钮所做的最后更改,并应用主题。基本上,我从上面更改的设置中获得了值:
var existingResourceDictionary = Application.Current.Resources.MergedDictionaries
.Where(rd => rd.Source != null)
.SingleOrDefault(rd => Regex.Match(rd.Source.OriginalString, @"(\/MaterialDesignThemes.Wpf;component\/Themes\/MaterialDesignTheme\.)((Light)|(Dark))").Success);
if (existingResourceDictionary == null)
throw new ApplicationException("Unable to find Light/Dark base theme in Application resources.");
var source =
$"pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.{(Settings.Default.Theme ? "Dark" : "Light")}.xaml";
var newResourceDictionary = new ResourceDictionary() { Source = new Uri(source) };
Application.Current.Resources.MergedDictionaries.Remove(existingResourceDictionary);
Application.Current.Resources.MergedDictionaries.Add(newResourceDictionary);代码工作正常,但我觉得我可以减少重复和缩短?
发布于 2018-06-26 12:15:10
你可以代替
如果(existingResourceDictionary.Source.ToString().Contains("Light")) { Settings.Default.Theme = true;Settings.Default.Save();} Settings.Default.Theme = false;Settings.Default.Save();}
通过
Settings.Default.Theme = existingResourceDictionary.Source.ToString().Contains("Light");
Settings.Default.Save();把它缩短一点。
https://codereview.stackexchange.com/questions/197272
复制相似问题