MasterPages: Improved Version(翻译)


原文的出处见http://authors.aspalliance.com/PaulWilson/Articles/?id=14

概览
MasterPages是最灵活和最易于使用的Page Template技术,它既然是由微软开发,将来很可能出现在ASP.NET中。可是,早期的Demo,缺乏设计时支持,性能也较差,并且NamingContainer技术会使ID形如Container:_ctl0:Region:Control此文演示一个改良版的MasterPages,含设计时支持,摒弃灵活但烦人的NamingContainer技术,增加如何定义默认content region和template file。

建立模板
要产生一个模板,首先你要产生一个让其它页面共享的asp.net用户控件,加入通用页面布局于其中。然后在页面布局中给出标识,标识此处需要由个别页面定义,由带有唯一ID的ContentRegion控件来标识,此ID往后用于匹配。只要你喜欢,你可以添加多个ContentRegion控件,而且能够添加普通的无需匹配的ID的Content控件进来。
Listing 1: Creating a Template
<%@ Control %>
<%@ Register TagPrefix="Wilson" Assembly="WilsonMasterPages"
    Namespace="Wilson.MasterPages" %>
<html>
<head>
  <title>MasterPages</title>
</head>
<body>
  <h1><wilson:contentregion id="MPHeader" runat="server">
    Page Header</wilson:contentregion></h1>
<form id="frmMain" method="post" runat="server">
  <wilson:contentregion id="MPContent" runat="server">
    Default Content</wilson:contentregion>
</form>
  <h2><wilson:contentregion id="MPFooter" runat="server">
    Page Footer</wilson:contentregion></h2>
</body>
</html>



默认定义
你能够在web.config定义两个默认设置,第一个Wilson.MasterPages.TemplateFile指定默认的模板控件
文件,第二个Wilson.MasterPages.DefaultContent指定默认的ContentRegion的ID,便于你直接添加控
件。默认ContentRegion的概念不是微软的想法,甚至在这里也是可选的,只是我个人觉得有用。


Listing 2: Defining the Defaults
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Wilson.MasterPages.TemplateFile" value="~/Template.ascx" />
    <add key="Wilson.MasterPages.DefaultContent" value="MPContent" />
  </appSettings>
  <system.web>
    <!-- Normal web.config settings go here -->
  </system.web>
</configuration>


应用模板
要使用这个模板,首先你要先建立一个空的asp.net页面,删除所有向导自动生成的代码。然后添加带有
TemplateFile属性的“MasterPage”控件。下一步,直接在MasterPage内增加默认的ContentRegion
控件。最后,添加其它ContentRegion控件,记得与模板中的ID匹配。
Listing 3: Using the Template
<%@ Page %>
<%@ Register TagPrefix="Wilson" Assembly="WilsonMasterPages"
    Namespace="Wilson.MasterPages" %>
<wilson:masterpage runat="server" TemplateFile="Template.ascx">
//原文此处为<wilson:masterpage runat="server" masterpagefile="Template.ascx">
//实际上原程序定义的是TemplateFile属性
//《MasterPage之超严重Bug——将导致窗体内带有回发事件的控件无法回发事件——以及解决方案》曾提及

<wilson:contentregion id="MPHeader" runat="server"> Sample Page</wilson:contentregion> Real Content for the Default ContentRegion </wilson:masterpage>


源代码要点


原来的MasterPage例子含ContentContainer和Region控件,他们都继承自PlaceHolder和
INamingContainer,以及继承自Panel的Content。可是,使用PlaceHolders的目的不是设计时支撑,
而是运行,所以,我的MasterPage继承自HtmlContainerControl,实现了一个ReadWrite Designer。
我将Content和Region这两个控件合二为一,成为一个单独的ContentRegion控件,它继承自Panel,我
为它增加了背景颜色。并且,去掉begin、end标记,以及INamingContainer接口定义。

结论
现在这个自定义MasterPage例子支持设计时,更快,并且增加了默认设置。但它仍然不具有可视化设计,那
样的话需要内建于VS.NET。需要注意的是,去调了INamingContainer,使其更快了,也避免了烦人的嵌套
命名,但会造成灵活性有所损失,不能监管命名的唯一性,不能进行模板嵌套。最后,到我的主页你会找到一
些可选择的生成模板的演示例子。




Author Bio
posted on 2005-12-04 18:43  lwj  阅读(595)  评论(0编辑  收藏  举报