2014-03-12 47 views
1

我在WPF(C#),其中所有的元素具有指向位於ResourceDictionary中的名稱爲「Styles.xaml」靜態資源的樣式wrriten程序;EXE之外使用XAML ResourceDictionary中的運作就像CSS文件

因爲我需要有風格customed,我用這個文件來改變顏色和字體都在整個計劃的元素。

的問題是,爲了見我需要重新編譯,並有另一個EXE至極輕微的不同版本的程序(由顏色不同)的變化。 我不想維護許多版本的程序。

是否有可能有一個ResourceDictionary中(或任何其他文件)編譯EXE之外充當CSS和HTML呢? 含義,是否有可能實現以下目的:替換EXE所在文件夾中的文件將足以改變顏色?

謝謝。

+0

我相信你可以創建一個DLL與相應的資源字典,然後使用反射從組件拉這一點,將它們添加到您的Application.Current.Resources.MergedDictionaries。 – TYY

回答

2

通過調用XamlReader.Load方法並在之後轉換結果對象,您可以從.xaml文件(不需要包含在您的項目中)獲得ResourceDictionary實例。從這一點開始,它就歸結爲在後面的代碼中操縱這本字典。在應用程序級別上,您可以調用類似

Application.Current.Resources.MergedDictionaries.Clear(); 
Application.Current.Resources.MergedDictionaries.Add(dictionary); 

其中字典是您已加載的實例。對於單個控件也可以做同樣的事情。

1

感謝Nikita Brizhak,我成功了。 這裏是完整的「如何」:

1)您需要添加一個OnStartUp方法App.xaml.cs.這裏是語法:

protected override void OnStartup(StartupEventArgs e) 

2)您必須清除所有資源。

Application.Current.Resources.Clear();//This is if you have on your App.xaml a load of your resource. Clear it and than load another. 
//It is good to have this so you can see you style while working on the project, But on runtime to replace. 
     Application.Current.Resources.MergedDictionaries.Clear(); 

3)你必須加載動態資源

終極密碼:

protected override void OnStartup(StartupEventArgs e) 
    { 
     base.OnStartup(e); 
     Application.Current.Resources.Clear(); 
     Application.Current.Resources.MergedDictionaries.Clear(); 
     StreamReader stream = new StreamReader("Styles.xaml"); 
     Application.Current.Resources.MergedDictionaries.Add(System.Windows.Markup.XamlReader.Load(stream.BaseStream) as ResourceDictionary); 
    } 
相關問題