यहां कोड का एक स्निपेट है जिसका उपयोग मैंने अपने एप्लिकेशन में किया था जो थीमिंग का समर्थन करता था। इस उदाहरण में, मेरे पास दो थीम हैं (डिफ़ॉल्ट और क्लासिक एक्सपी)। विषय संसाधन डिफ़ॉल्टथीम.एक्सएमएल और क्लासिकथीम.एक्सएमएल क्रमशः संग्रहीत हैं।
यह App.xaml मैं विषय बदलने के लिए अनुमति देने के लिए निम्न विधि है पीछे कोड में तब मेरे App.xaml
<Application ...>
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ArtworkResources.xaml" />
<ResourceDictionary Source="DefaultTheme.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style x:Key="SwooshButton" TargetType="ButtonBase">
<!-- style setters -->
</Style>
<!-- more global styles -->
</ResourceDictionary>
</Application.Resources>
</Application>
में डिफ़ॉल्ट कोड है। असल में, आप जो करते हैं वह संसाधन शब्दकोश साफ़ करता है और फिर नई थीम के साथ शब्दकोश को पुनः लोड करता है।
private Themes _currentTheme = Themes.Default;
public Themes CurrentTheme
{
get { return _currentTheme; }
set { _currentTheme = value; }
}
public void ChangeTheme(Themes theme)
{
if (theme != _currentTheme)
{
_currentTheme = theme;
switch (theme)
{
default:
case Themes.Default:
this.Resources.MergedDictionaries.Clear();
AddResourceDictionary("ArtworkResources.xaml");
AddResourceDictionary("DefaultTheme.xaml");
break;
case Themes.Classic:
this.Resources.MergedDictionaries.Clear();
AddResourceDictionary("ArtworkResources.xaml");
AddResourceDictionary("ClassicTheme.xaml");
break;
}
}
}
void AddResourceDictionary(string source)
{
ResourceDictionary resourceDictionary = Application.LoadComponent(new Uri(source, UriKind.Relative)) as ResourceDictionary;
this.Resources.MergedDictionaries.Add(resourceDictionary);
}
क्या आप भी इस दृष्टिकोण के साथ ध्यान में रखने की आवश्यकता होगी कि किसी भी शैली है कि एक विषय का उपयोग एक गतिशील संसाधन की आवश्यकता होगी है। उदाहरण के लिए:
<Window Background="{DynamicResource AppBackgroundColor}" />
शानदार उत्तर, मैंने इसे कार्यान्वित किया है, मैं सोच रहा था कि आप बाध्य बटन छवियों को बदलने के लिए इसका उपयोग कैसे करेंगे। मैंने यहां एक प्रश्न पूछा है: http://stackoverflow.com/questions/39795317/how-do-i- गतिशील रूप से-change-which-resource-folder-i-get-an-image-from – AidanO