2009-06-12 20 views
0

我有一個應用程序,允許用戶更改基於外部xaml文件的配色方案。當用戶點擊包含主題名稱的菜單項,下面的代碼執行:如何獲取資源更改以傳播整個應用程序,包括ValueConverters?

MenuItem mi = sender as MenuItem; 
string executingDirectory = Assembly.GetExecutingAssembly().Location.Substring(0, Assembly.GetExecutingAssembly().Location.LastIndexOf("\\")); 
string path = System.IO.Path.Combine(executingDirectory + "\\Themes", mi.Header.ToString() + ".xaml"); 

if (File.Exists(path)) 
{ 
    using (FileStream fs = new FileStream(path, FileMode.Open)) 
    { 
     ResourceDictionary dic = (ResourceDictionary)XamlReader.Load(fs); 
     Resources.MergedDictionaries.Clear(); 
     Resources.MergedDictionaries.Add(dic); 
    } 
} 

這適用於大多數的應用程序 - 我所有的資源刷的改變 - 有一個例外。我有一個子控件,其背景色是由一個使用轉換器的值綁定來確定的。而不是硬編碼的顏色到轉換器,不過,我有刷名轉換器使用字符串常量,然後返回從App.Current.Resources顏色:

Brush ret = Application.Current.Resources[brushToReturn] as Brush; 

什麼似乎是這裏發生的是, Application.Current.Resources沒有保存與該窗口相同的一組資源。我曾嘗試將主題加載到Application.Current.Resources中,並從轉換器中讀取該主題,但似乎也無法工作。誰能告訴我我在這裏失蹤了什麼?有沒有辦法改變Application.Current.Resources並讓它影響打開的窗口?

謝謝!

回答

0

很難說沒有看到你所有的代碼,但檢查Resources屬性不會自動檢查合併字典。另外,如果您將主題資源合併到Window級別,那麼它們根本就不在應用程序級別。爲了一致性起見,你最好讓你的轉換器得到它正在轉換爲元素的保持和使用FindResource

var frameworkElement = values[0] as FrameworkElement; 
var resource = frameworkElement.FindResource("SomeKey") as Brush; 

使用的IMultiValueConverter可能是您最好的選擇。另外,如果這太麻煩了,你可能會考慮編寫一個標記擴展來滿足你的需求。

相關問題