The MasterPage doesn’t have a property for setting the Theme at design time. Despite this, I wanted to set the Theme for a MasterPage, so I decided to set it from code. I was aware of the possibility to set the Theme through the web.config, but that wasn’t the way I wanted to set it. One of the reasons being it would result in the theme being applied to the entire website.

I tried to use the Page_Load, but that resulted in the error “The ‘Theme’ property can only be set in or before the ‘Page_PreInit’ event.”. That sounds logical, because the Theme makes the Page render in a specific way. So I added a Page_PreInit method with the right parameters, but that didn’t do anything. As it turns out, the Master Page doesn’t have a Page_PreInit…

To be able to set the Theme for a MasterPage from code, follow these steps:

  1. Add a class with the name ThemeModule (or any other name)
  2. Let the class inherit from IHttpModule
  3. Implement the init method as follows:

    public void Init(HttpApplication context)
    {
        context.PreRequestHandlerExecute += HandlePreRequest;
    } 

  4. void HandlePreRequest (object sender, EventArgs e)
    {
        Page page = HttpContext.Current.CurrentHandler as Page;
        if (page != null)
        {
            page.PreInit += delegate
                                {
                                    page.Theme = DetermineTheme();
                                };
        }
    }

  5. Add the HttpModule to your web application through the web.config:

     
    <
    httpModules>
        <add name=ThemeModule type=Howtos.ThemeModule/>
      </httpModules>

That’s it! Hope this helps.

A week ago I came up with this solution together with a good friend of mine. The code was on his machine, so he said I had to add a ‘thanks to’ in this post. Well, here it is: thanks 2 Sander van Kemenade! ;)