Silverlight 4 – Implicit Styles and Themes

I hadn’t really thought properly about implicit styles in Silverlight 4 although I wrote a little about it back here and it’s something that WPF always had ( if I remember correctly ).

The bit that I hadn’t really thought about was how you could set up a set of implicit styles for all your controls, throw them into separate resource dictionaries and then just load one style or the other at runtime and push it into the MergedDictionaries property of your application’s ResourceDictionary. It’s fairly obvious so I don’t think I’m stating anything new but I just hadn’t really thought about it.

Also, of course, the Silverlight Toolkit already has this sort of theming support for both Silverlight 3 and 4.

You might load those resource dictionaries from embedded XAML files in your assembly or XAP or it might be from loose XAML files that you load from the file system or from the web.

As a simple example, below is an “app” which displays a few controls and then offers the chance to load one of 2 XAML files ( based on the ListBox selection ) from the site-of-origin in order to change the application’s theme.

The code’s pretty simple with the heart of it being something like this;

 void ChangeDictionary()
    {
      IsBusy = true;

      WebClient client = new WebClient();

      client.DownloadStringCompleted += (s, e) =>
        {
          if (!e.Cancelled && (e.Error == null))
          {
            try
            {
              ResourceDictionary dictionary = XamlReader.Load(e.Result) as ResourceDictionary;

              if (dictionary != null)
              {
                Application.Current.Resources.MergedDictionaries.Clear();
                Application.Current.Resources.MergedDictionaries.Add(dictionary);
              }
            }
            catch (XamlParseException)
            {
            }
            finally
            {
              IsBusy = false;
            }
          }
        };

      client.DownloadStringAsync(new Uri(selectedDictionaryFile, UriKind.Relative));
    }

which just sets a busy flag ( for a BusyIndicator control ) and then downloads the XML file containing the ResourceDictionary asynchronously and slots it into the application’s resources.

The code’s here for download.