日期:2012-01-30  浏览次数:20471 次

ASP.NET Server Control Design Time Support

做过自己的 asp.net server control 了吗?有没有象 ASP.NET DataGrid 控件那样:
1。从 Toolbox 一拽出来,自动产生一堆代码
2。right click 看属性时,有一大堆 custom attribute
3。还能进入 template edit 模式把 toolbox 里的 textbox 之类的东东拽到你的控件中
4。甚至还能弹出一个自己的对话框来做巨复杂的配置

我花了一天时间来看如何做这些东东,虽然最后发现目前我不需要这些 features 但是还是
愿意和大家分享一下,有些东东你不去看真的不知道原来如此简单,正如同有些东西你看完
发现居然如此复杂一样。

主要文档: (注意 url 换行)
msdn lib: Enhancing Design-Time Support
http://msdn.microsoft.com/library/default.asp?
url=/library/en-us/cpguide/html/cpconenhancingdesign-timesupport.asp
PDC02 session 407 名字好像是 build asp.net server control 之类的。

msdn 文档第一段里就开门见山说:
In the .NET Framework, the work for design-time support is not delegated to a
design environment such as Visual Studio .NET but is enabled through a rich
built-in design-time architecture.

所以你要做的东东不是什么 vs.net add-on,而是直接扩展你的控件。

1。从 Toolbox 一拽出来,自动产生一堆代码
  这件事情是通过在你的 server control 代码里加个 attribute 实现的:
  (要不怎么说 attribute programming 呢)
     [ToolboxData("<{0}:myControl runat=server></{0}:myControl>")]
     public class myControl : System.Web.UI.WebControls.DataGrid // 随便举个例子
  这样你把你的控件拽到 webform 里面时,它就会自动生成这些代码乐。

2。right click 看属性时,有一大堆 custom attribute
   比如说你的控件里面有个属性是指定 xsl file 的 url,你可以这样:
    [
    Browsable(true),
    Category("Data"),
    DefaultValue("http://myserver/myApp/myXSL.xsl"),
    Description("specify your XSL file URL"),
    Editor(typeof(System.Web.UI.Design.XslUrlEditor),
    typeof(System.Drawing.Design.UITypeEditor))
    ]
    public string MyXSLTSrc {...}
   如此这般,你就可以在属性对话框的 data 组中看到你的 MyXSLTSrc 乐,
   而且你可以通过一个专门的选 xsl url 的对话框来指定这个值乐。

3。还能进入 template edit 模式把 toolbox 里的 textbox 之类的东东拽到你的控件中
   免费午餐结束了。剩下东东真的要写代码了。
   首先得告诉控件你为它老人家专门作了个 designer:
   [ Designer("YourNameSpace.Design.MyControlDesigner, YourNameSpace") ]
    public class myControl : System.Web.UI.WebControls.DataGrid // 随便举个例子

   然后真的给它老人家做个 Designer:
   namespace YourNameSpace.Design
   {
      public class MyControlDesigner : System.Web.UI.Design.WebControls.DataGridDesigner    
      { // 由于 control 是从 DataGrid 继承的,control designer 也就从 DataGridDesigner 继承
      }
   }
   
   这个 designer 主要要做什么事情呢?
   你至少要 render 出一段 html code 来,这样在 VS.NET IDE 的 design view 里你才能看见
   您老辛辛苦苦做的 control。
   主要通过 override 这些 methods:
   public override string GetDesignTimeHtml()
   protected override string GetEmptyDesignTimeHtml()

   比如你的控件支持 data binding 什么的,你可以考虑使用一些 sample data 去显示。
   或者多做些工作真的把 page developer 指定的 data source 绑定了显示出来。

   仔细看文档你就会发现如何建立 edit template。做了 edit template 后你 right click 你的
   控件就可以进入编辑模式,比如你的控件中包含一个 content template,你就可以把 toolbox 里
   的 asp.net textbox, checkbox 之类的东东直接 drag & drop 到里面去乐。

4。甚至还能弹出一个自己的对话框来做巨复杂的配置
   要想实现这个还要多花些功夫,你必须再做一个 MyControlComponentEditor,
   public class MyControlComponentEditor : System.Web.UI.Design.WebControls.DataGridComponentEditor  
   并且告诉 myCo