2

How can I change Page.Theme dynamically in UserControl?

As far as I know it can be done in Page_PreInit but UserControl dont have such an event, it`s exists only in Page class.

liron
  • 375
  • 2
  • 12

2 Answers2

3

MSDN says:

You must be aware of one restriction when using the theme property. The theme property can only be set during or before the Page PreInit event.

The user control life cycle starts right after the page's PreInit event, so you won't be able to set the theme directly from your control.

But still there is a little workaround: assuming the current theme is stored in the session object, you could change this session value in any place of your user control, then just refresh the page e.g. by using Response.Redirect(Request.Url.AbsoluteUri) and change the theme in the Page_PreInit handler:

Here is page's PreInit event handler:

protected void Page_PreInit(object sender, EventArgs e)
{
    var theme = Session["Theme"] as string;
    if (theme != null) 
    {
        Page.Theme = theme;
    }
}

and e.g. OnSelectedIndexChanged event handler in your user control:

protected void ddlTheme_SelectedIndexChanged(object sender, EventArgs e)
{
    Session["Theme"] = ddlTheme.SelectedValue;
    Response.Redirect(Request.Url.AbsoluteUri);
}
Oleks
  • 31,955
  • 11
  • 77
  • 132
  • The `Response.Redirect(Request.Url.AbsoluteUri);` will give us an infinite loop. We need to check `if (Session["Theme"] != ddlTheme.SelectedValue)` – liron Apr 26 '11 at 12:00
  • Yes, `Response.Redirect` will give you an infinite loop if you use it in a code which executes on every page processing. In the example above, it is assumed to be executed on a postback only. But yes, you're right that the value needs to be checked. – Oleks Apr 26 '11 at 12:04
0

On user control load event, use:

this.ApplyStyleSheetSkin(Page);
oragorn
  • 181
  • 1
  • 7
  • It`s not answered my question... I want to change the theme dynamically from OnLoad of the UserControl. `Page.Theme = "MyCustomTheme";` – liron Apr 26 '11 at 10:40