2012-11-30 31 views
1

總之,我的問題是:如何在WP7.1應用程序中切換ResourceDictionaries?有沒有比我想要做的更簡單的方法?基於用戶當前主題的Windows Phone(7.1)「蒙皮」

詳細...

在Windows Phone 7的項目,我需要根據用戶的主題(光/暗)來代替應用程序資源。簡單地說這個想法是顯而易見的:
一)建立資源字典變量
二)根據當前主題
三)上述資源添加到Application.Current.Resources.MergedDictionaries得到適當的樣式和畫筆資源文件

下面是我在做什麼:

1)的文件夾結構的資源,在 「查看」 項目:
資源
黑暗
Brushes.xaml
Styles.xaml

Brushes.xaml
Styles.xaml

2)在2個Brushes.xaml文件的樣式具有相同的密鑰。與Styles.xaml相同。

3)在我第一次嘗試(假設選擇燈光主題)時,第二行出現「未指定的錯誤」。

var uriPath = "Resources/Light/Brushes.xaml"; 
var brushes = new ResourceDictionary {Source = new Uri(uriPath, UriKind.Relative)}; 
dic.MergedDictionaries.Add(brushes); 

(FYI我試着用資源,頁面和內容建設的行動)

4)我的第二次嘗試給了我希望,當我成功設法東西Brushes.xaml進入App的MergedDictionaries:

string xaml; 
var uriPath = "Resources/Light/Brushes.xaml"; 
var brushesUri = new Uri(uriPath, UriKind.Relative); 
var brushesStream = Application.GetResourceStream(brushesUri); 
using (var brushesStreamReader = new StreamReader(brushesStream.Stream)) 
    xaml = brushesStreamReader.ReadToEnd(); 
var dic = new ResourceDictionary(); 
dic.MergedDictionaries.Add((ResourceDictionary)XamlReader.Load(xaml)); 

5)爲了brushesStreamReader不是null在上面的代碼中我必須將xaml文件設置爲「內容」。 (爲什麼?)

6)我的代碼在第4步中的第二個問題是當試圖用Styles.xaml做同樣的事情。在最後一行(dic.MergedDictionaries.Add ...)我得到一個「Failed to assign to property 'System.Windows.ResourceDictionary.Source'」。也許這是因爲Styles.xaml將Brushes.xaml添加到它自己的MergedDictionaries中:

<ResourceDictionary.MergedDictionaries> 
    <ResourceDictionary Source="Brushes.xaml"/> 
</ResourceDictionary.MergedDictionaries> 

是嗎?
謝謝!

回答

-1

你不應該這樣做。只需使用系統畫筆即可獲取所有主題顏色。 下面是這些畫筆的一個很好的概述:http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769552.aspx#BKMK_BrushResources

+0

謝謝,但這不能回答我的問題。使用系統刷子非常有限。如果您想要顯示不同的動畫,或根據主題呈現不同的控件,該怎麼辦?或者簡單地說,如果您想在「淺色」模式下以紅色陰影顯示視覺元素的所有口音,在「黑暗」模式下時要顯示其他調色板中的所有色調? –

0

在這種情況下,你可以抓住主題畫筆並分析它。例如:

private Color lightThemeBackground = Color.FromArgb(255, 255, 255, 255); 
private Color darkThemeBackground = Color.FromArgb(255, 0, 0, 0); 


public bool IsLightTheme() 
{ 
    SolidColorBrush backgroundBrush = Application.Current.Resources["PhoneBackgroundBrush"] as SolidColorBrush; 
    if (backgroundBrush.Color == lightThemeBackground) { 
      // you are in the light theme 
      return true; 
    } 
    else { 
      // you are in the dark theme 
      return false; 
    } 
}