2017-08-23 37 views
0

我有一个简单的WPF应用程序来更改颜色主题。WPF Color Theme

ResourceDictionary blueDict = new ResourceDictionary() { Source = new Uri(@"/Styles/Colors/Blue/BlueColors.xaml", UriKind.Relative) }; 
ResourceDictionary greenDict = new ResourceDictionary() { Source = new Uri(@"/Styles/Colors/Green/GreenColors.xaml", UriKind.Relative) }; 
ResourceDictionary yellowDict = new ResourceDictionary() { Source = new Uri(@"/Styles/Colors/Yellow/YellowColors.xaml", UriKind.Relative) }; 
ResourceDictionary genericDict = new ResourceDictionary() { Source = new Uri(@"/Styles/Colors/GenericColors.xaml", UriKind.Relative) }; 

在MainWindow上我有一个ComboBox存储三个枚举值“蓝色,绿色,黄色”。这就是它的时候所选择的指标发生了变化:

Application.Current.Resources.MergedDictionaries.Clear(); 
Themes newTheme = (Themes)cbxThemes.SelectedItem; 

if (newTheme == currentTheme) 
    return; 

switch (newTheme) 
{ 
    case Themes.Blue: 
     Application.Current.Resources.MergedDictionaries.Add(blueDict); 
     break; 

    case Themes.Green: 
     Application.Current.Resources.MergedDictionaries.Add(greenDict); 
     break; 

    case Themes.Yellow: 
     Application.Current.Resources.MergedDictionaries.Add(yellowDict); 
     break; 

    default: 
     break; 
} 

Application.Current.Resources.MergedDictionaries.Add(genericDict); 

currentTheme = newTheme; 

第一次,一切正常,我可以选择我想要的颜色,但是当我再次改变颜色,没有任何反应。

有没有什么不在后台更新?

该代码有效,如果输出Application.Current.Resources.MergedDictionaries,您甚至可以看到新的来源。只有用户界面不会更新。

+0

你是如何引用xaml中的资源的? – MikeT

+0

请参阅https://social.msdn.microsoft.com/Forums/vstudio/en-US/44e80e86-9c62-4b77-87bc-00997a4796f4/change-in-applicationcurrentresourcesmergeddictionaries-is-n--visually-updating?forum=wpf – MikeT

回答

0

我找到了一个解决方案:

只需更换

Application.Current.Resources.MergedDictionaries.Add(yourDictionary); 

Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(@"yourPath.xaml", UriKind.Relative) }); 

作为结束在编程中,我不知道它为什么起作用,但首先我很高兴。如果有人能向我解释这个,那会很棒。

0

尝试更换这行:

Themes newTheme = (Themes)cbxThemes.SelectedItem; 

这一行:

string newTheme = ((ComboBoxItem)cbxThemes.SelectedItem).Content.ToString(); 

Ofcourse,你也只需要修改你如何处理newTheme和currentTheme之间的比较。

如果你不想使用一个字符串,你可以把它使用到枚举:

Themes newTheme; 
Enum.TryParse(((ComboBoxItem)cbxThemes.SelectedItem).Content.ToString(), out newTheme); 
+0

无法投射'StyleThemes.Themes'类型的对象来键入'System.Windows.Controls.ComboBoxItem'。 我设置了cbxThemes.ItemsSource = Enum.GetValues(typeof(Themes)); 所以项目是主题的类型。 –

+0

@ j.zeddi然后,而不是像上面所做的那样强制转换为ComboBoxItem,请使用:cbxThemes.SelectedValue.ToString() – Hubbs

+0

hm ...没有例外,但问题仍然存在。 –