2017-08-23 58 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 ...沒有例外,但問題仍然存在。 –