2013-03-04 55 views
0

如何在Silverlight中使用動態ResourceDictionary源代碼?我的應用程序有一個「Styles.xaml」有很多的樣式定義並引用了幾個刷,定義了「Colors.xaml」:如何在Silverlight中使用動態ResourceDictionary源代碼?

Styles.xaml:

<ResourceDictionary> 
    <ResourceDictionary.MergedDictionaries> 
    <ResourceDictionary Source="/Project;component/Colors.xaml" /> 
    </ResourceDictionary.MergedDictionaries> 
    <DataTemplate x:Key="MyLayoutTemplate"> 
    <Button Background="ButtonBackgroundBrush">Button Title</Button> 
    </DataTemplate> 
    <!-- A lot of other definitions --> 
</ResourceDictionary> 

Colors.xaml:

<ResourceDictionary> 
    <SolidColorBrush x:Key="ButtonBackgroundBrush" Color="#FFFFFFFF"/> 
    <!-- ... --> 
</ResourceDictionary> 

所以基本上Styles.xaml定義了佈局,Colors.xaml定義了顏色(duh)。我的App.xaml只引用這個Styles.xaml。

我需要的是一種方法,不使用此:

<ResourceDictionary Source="/Project;component/Colors.xaml" /> 

和「點」(或綁定)此Source屬性到這將是動態定義靜態類。像這樣的東西:

<ResourceDictionary Source="{Binding Settings.ThemeUri}" /> 

有什麼辦法可以實現這個嗎?

回答

0

只能在XAML中實現這一點,但在代碼中創建字典很簡單。

ResourceDictionary styleDictionary = new ResourceDictionary() 
{ 
    Source = new Uri("/Project;component/Styles.xaml", UriKind.Absolute) 
}; 
ResourceDictionary colorDictionary = new ResourceDictionary() 
{ 
    Source = new Uri("/Project;component/Colors.xaml", UriKind.Absolute) 
}; 

styleDictionary.MergedDictionaries.Add(colorDictionary); 
Application.Current.Resources.MergedDictionaries.Add(styleDictionary); 
+0

感謝您的回答,但它沒有奏效。查看其中的Styles.xaml引用Colors.xaml。 – 2013-03-05 19:58:11

+0

我認爲這只是因爲我在示例中混合了URI。現在修復。 – 2013-03-05 20:01:15

+0

再次感謝,但它仍然無法正常工作。我希望能夠在運行時選擇採用除Colors.xaml之外的xaml的顏色方案。問題是Styles.xaml有對Colors.xaml的這個硬引用。 – 2013-03-05 20:14:46

相關問題