2010-08-16 44 views
1

我有一個簡單的WPF應用程序用於實驗。更改ResourceDictionary不會影響WPF中的窗口

我有兩個主題在單獨的xaml文件中定義,更改xaml指向他們工作正常。順便說一下,在xaml中,我使用的是直接ResourceDictionary元素,而不是ResourceDictionary.MergedDictionaries

我想讓用戶選擇使用哪個主題,因此我將代碼中的源屬性重置 - 但調試器告訴我我已成功設置應用程序外觀的值不會更改。

那麼,如何在運行時成功應用主題?

編輯:這是我如何聲明在XAML我的「風格」:

<Window x:Class="WpfUI.winMain"> 
    <Window.Resources> 
    <ResourceDictionary Source="Themes\Blah.xaml"></ResourceDictionary> 
    </Window.Resources> 

    // The windows grid and other controls... 

</Window> 
+0

製作新的ResourceDictionary(在代碼中)並調用ApplyTemplate()成功應用主題/樣式 - 但不是所有控件。 – 2010-08-16 05:13:39

回答

1

簡單的回答是,你需要清除應用程序合併資源字典。下面是一些代碼來獲取如果你想要一個非常好的打包的解決方案,你開始

ResourceDictionary dictionary = GetThemeResourceDictionary(yourTheme) 

if (dictionary != null) 
{ 
    App.Current.Resources.MergedDictionaries.Clear(); 
    App.Current.Resources.MergedDictionaries.Add(dictionary); 
} 

public ResourceDictionary GetThemeResourceDictionary(string theme) 
{ 
    if (theme != null) 
    { 
     Assembly assembly = Assembly.LoadFrom("WPF.Themes.dll"); 
     string packUri = String.Format(YourThemeFolder/{0}.xaml", theme); 
     return Application.LoadComponent(new Uri(packUri, UriKind.Relative)) as ResourceDictionary; 
    } 
    return null; 
} 

,我會reccommend WPF themes。它引入了一個ThemeManager類和一組真正令人難以置信的內置主題。如果在安裝或添加新主題時遇到困難,請聯繫我:)

+0

很酷 - 謝謝!讓我檢查一下。 – 2010-08-16 03:10:31

+0

嗯 - 似乎沒有爲我工作 - 是我如何在xaml中指定ResourceDictionary? (我已經將它添加到問題 - 對不起,這不是在這臺機器上,所以不容易複製整個代碼) – 2010-08-16 03:35:07

+0

AAh kk我得到了你。問題是,這個解決方案是爲了將主題應用程序廣泛應用。有幾件事要檢查。首先,驗證您是否收到資源字典。其次,用WPFui.winMain.Resources替換App.Current.Resouces。您想要清除您在該特定窗口中擁有的資源。我會推薦廣泛應用風格的應用程序。您可以通過使用Application.Resources來完成此操作。 – TerrorAustralis 2010-08-16 05:23:26