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.
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);
}
On user control load event, use:
this.ApplyStyleSheetSkin(Page);