Dynamic Theme in Silverlight 3
One of the features of WPF that we might be keen in implementing in Silverlight is changing the themes dynamically at runtime. So let us understand how to achieve toggling of theme on a Silverlight Page / User Control.
- Install Silverlight Toolkit from http://www.codeplex.com/Silverlight
- Let's place a button in our XAML to toggle the themes. This button will be called 'btnThemeChanger'
- We will define a private class variable as: private bool isBlackTheme = false;
- Now we create folder 'XAML' in our solution and place two files in the folder:
System.Windows.Controls.Theming.ExpressionDark.xaml
System.Windows.Controls.Theming.ExpressionLight.xaml
(Both these XAML files are shipped with Silverlight Toolkit) - In the project, add a reference to System.Windows.Controls.Theming.Toolkit.dll
- Adding code to this btnThemeChanger_Click:
[sourcecode language='csharp']
private void btnThemeChanger_Click(object sender, RoutedEventArgs e)
{
Uri uri;
if (!isBlackTheme)
{
uri = new Uri(@"XAML/System.Windows.Controls.Theming.ExpressionDark.xaml", UriKind.Relative);
isBlackTheme = true;
}
else
{
uri = new Uri(@"XAML/System.Windows.Controls.Theming.ExpressionLight.xaml", UriKind.Relative);
isBlackTheme = false;
}
ImplicitStyleManager.SetResourceDictionaryUri(mainContainer, uri);
ImplicitStyleManager.SetApplyMode(mainContainer, ImplicitStylesApplyMode.Auto);
ImplicitStyleManager.Apply(mainContainer);
}
[/sourcecode]
Execute this project and see the themes change :)