2012-12-06 38 views
1

我的UI由一組樣式定義。交換全球XAML樣式/主題

我想給用戶從兩種風格家族中進行選擇。

如何在代碼背後替換全局樣式?

+0

自定義主題,不支持(至少知道了)http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/ba77cedb-b90b-49a2-af00-aba9e14dcef2 –

回答

3

密切關注依賴關係,以便資源不會嘗試引用尚未定義的其他資源。查看Merged Dictionaries上的部分以查看何時加載的內容。此外,您將不得不將所有資源從App.xaml移到通用資源字典中,因爲當您將應用程序資源重置爲新的合併字典時,它們將被清除。

更新只在重新創建元素時才起作用,因此需要導航才能應用更改。

private void LoadStyles(StyleType styleType) 
{ 
    ResourceDictionary merged = new ResourceDictionary(); 
    ResourceDictionary generic = new ResourceDictionary(); 
    ResourceDictionary theme = new ResourceDictionary(); 

    generic.Source = new Uri("ms-appx:/Common/StandardStyles.xaml"); 

    switch (styleType) 
     { 
      default: 
      case StyleType.Custom1: { theme.Source = new Uri("ms-appx:/Common/AppStyles-Custom1.xaml"); break; } 
      case StyleType.Custom2: { theme.Source = new Uri("ms-appx:/Common/AppStyles-Custom2.xaml"); break; } 
      case StyleType.Custom3: { theme.Source = new Uri("ms-appx:/Common/AppStyles-Custom3.xaml"); break; } 
     } 

    merged.MergedDictionaries.Add(generic); 
    merged.MergedDictionaries.Add(theme); 

    App.Current.Resources = merged; 

    //this.ApplyTemplate(); <- doesn't seem to reapply resources to layout tree 
} 
+0

我試圖做到這一點,但主題沒有得到應用,除非我在App.xaml.cs中設置它。如果我在其他地方設置它不起作用。有沒有辦法立即應用它? –

3

以下文章可以幫助:

一般來說,你需要從可能的另一個組件,新的資源來代替App.Resources.MergedDictionaries在運行時,在列表重新應用模板在MainWindow的級別,一定要有DynamicResource在你的風格assignements。下面的算法可以幫助你:

  1. 清潔App.Resources.MergedDictionaries
  2. 填寫App.Resources.MergedDictionaries新集ResourceDictionary
  3. 再塗窗口模板與mainWindow.ApplyTemplate();

希望這有助於。

+0

適用於Windows 8 WinRT? –

+0

其可能性。我前段時間玩過這個遊戲,並且開始工作。如果我找到代碼,我將分享 – kindasimple