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:

 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);

        }

Execute this project and see the themes change :)

 

Related posts:

Continue reading » · Written on: 12-16-09 · 3 Comments »

3 Responses to “Dynamic Theme in Silverlight 3”

  1. Prasad wrote:

    Hi,
    In SL4 support for ImplicitStyleManager is removed,it supports implicit styles natively.
    you can check this out here

    http://blogs.msdn.com/delay/archive/2009/11/18/silverlight-4-beta-is-out-and-the-toolkit-has-it-covered-silverlight-toolkit-november-2009-release-now-available-for-silverlight-3-and-4.aspx

    Now if i want to change a theme on selection change event of combobox,how can i do this using silverlight 4.

    can you give me some information about this?

    December 23rd, 2009 at 3:47 pm
  2. Punit Ganshani wrote:

    Hi Prasad,

    Thanks for writing to me. By inline styles, it means styles can now be accessed using its object or we can have XAML tag called Style in the XAML files.

    For more read, please visit http://msdn.microsoft.com/en-us/library/cc645083(VS.96).aspx

    Thanks,
    Punit

    December 24th, 2009 at 10:12 am
  3. Adieu 2009! | ganshani.com wrote:

    [...] Dynamic Themes in Silverlight 3 [...]

    January 4th, 2010 at 2:11 pm

Leave a Reply