那么我们可以定一个基类,在这个基类中去做这件事,然后让所有的页面继承这个基类;又因为页面是一定要继承自System.Web.UI.Page类的,所以这个基类也必须继承自System.Web.UI.Page。现在在AppCode中再建一个文件 PageBase.cs:
// 供所有基类继承 public class PageBase : Page { protected StyleTemplateConfiguration styleConfig; protected string userStyle; // 用户设置的风格 protected string userTheme; // 用户设置的主题 protected IUserStyleStrategy userStrategy; // 使用何种算法来获得用户自定义的信息 protected override void OnPreInit(EventArgs e) { base.OnPreInit(e);
// 这里会被缓存只在第一次时调用有用 this.styleConfig = (StyleTemplateConfiguration)ConfigurationManager.GetSection("styleTemplates");
// 当你实现了自己的 Strategy时只需要更改这里就可以了 // 更好的办法是将Stragey的类型保存在Web.config中, // 然后使用反射来动态创建 userStrategy = new DefaultStyleStrategy("userStyle");
// 获取用户风格 userStyle = userStrategy.GetUserStyle();
// 如果用户没有设置风格,使用默认风格 if (String.IsNullOrEmpty(userStyle)) { userStyle = styleConfig.DefaultStyle; userTheme = styleConfig.DefaultTheme; } else { // 根据用户设置的风格 获取 主题名称 userTheme = styleConfig.GetTheme(userStyle); }
// 根据当前页获取MasterPage的路径 string masterPagePath = styleConfig.GetMasterPage(userTheme);
// 设置当前页的MasterPage if (masterPagePath != null) this.MasterPageFile = masterPagePath;
this.Theme = userTheme; // 设置当前页的主题 } }
这里需要注意:
ConfigurationManager.GetSection()方法只会调用一次,然后会将结果进行缓存;只要Web.Config不做修改,以后不管是Request还是PostBack都不会再重新生成StyleTemplateConfig的类型实例,而会从缓存中读取。我在《.Net 自定义应用程序配置》中忘记说了。
userStrategy = new DefaultStyleStrategy("userStyle");这里可以将IUserStyleStrategy的类型信息保存在Web.config中,然后使用反射动态创建。具体方法依然参见《.Net 自定义应用程序配置》。
如果想动态地为页面设置主题和模板,代码必须写在PreInit事件中。参见《Asp.Net Page Life Cycle Overview》。
效果预览
因为这只是一个范例程序,我主要是表达实现的思路,而不是代码的编写,所以省略了很多诸如结点属性是否为空之类的判断。下面的测试仅仅在Web.Config中的配置正确时。在站点下新建一个页面,比如Default.aspx,注意创建一个模板页,因为这里设置的是会被覆盖的,所以无所谓选择哪个模板。
添加App_Theme下创建目录Default、Spring,新建一个目录MasterPage,在下面创建目录Default、Spring,然后添加一些文件(这就不用我说了吧)。在页面上添加一个DropDonwList,一个Button,当我们选择要显示的模板时,会进行相应的切换,编写后置代码:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) { ltrStyleName.Text = userStyle;
foreach (string styleName in styleConfig.StyleNames) { ListItem item = new ListItem(styleName); if (string.Compare(styleName, userStyle) == 0) item.Selected = true; ddlStyles.Items.Add(item); } } }
// 更换风格 protected void Button1_Click(object sender, EventArgs e) { string styleName = ddlStyles.SelectedValue; userStrategy.ResetUserStyle(styleName); // 委托给userStragety去处理 }
之后你可以看到下面的画面:


可以通过下面这个连接来看实际的效果,注意到:在这里我让 Default.aspx 和 Other.aspx 使用了同一个模板,你也可以设置它们使用不同的模板。
总结
在这篇文章中,我简单地向大家介绍了实现网站风格切换的一个思路。
(编辑:焦作站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|