博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

asp.net组件(3):RenderControl,Render,RenderChildren三者的关系

Posted on 2007-12-18 18:15  a-peng  阅读(1888)  评论(2编辑  收藏  举报
我们主要研究RenderControl,Render,RenderChildren的执行顺序.
三者的含义从他们的命名可以很清楚的看出.
RenderControl绘制控件
Render绘制
RenderChildren绘制子控件
看下面的代码
public class UserComponent : Control
{
    public UserComponent()
    { 
    }

    public override void RenderControl(HtmlTextWriter writer)
    {
        writer.Write(@"<script language='javascript'>alert('RenderControl');</script>");
        //base.RenderControl(writer);
    }


    protected override void Render(HtmlTextWriter writer)
    {
        writer.Write(@"<script language='javascript'>alert('Render');</script>");
        //base.Render(writer);

    } 

    protected override void RenderChildren(HtmlTextWriter writer)
    {
         writer.Write(@"<script language='javascript'>alert('RenderChildren');</script>");
         //base.RenderChildren(writer);
    }
}
运行程序:只弹出对话框 RenderControl
说明:最先被调用的是 RenderControl 绘制控件

将base.RenderControl(writer);的注释去掉
public override void RenderControl(HtmlTextWriter writer)
{
   writer.Write(@"<script language='javascript'>alert('RenderControl');</script>");
   base.RenderControl(writer);
}
运行程序:弹出对话框 RenderControl 然后弹出对话框 Render
说明:控件通过 RenderControl 调用了 Redner

将base.Render(writer);的注释去掉
protected override void Render(HtmlTextWriter writer)
{
        writer.Write(@"<script language='javascript'>alert('Render');</script>");
        base.Render(writer);
} 
运行程序:弹出对话框 RenderControl 然后弹出对话框 Render 然后弹出对话框 RenderChildren
说明:控件通过 RenderControl 调用了 Redner 调用 RenderChildren

现在来看下面的代码,应该有些感觉了吧...
using System;
using System.Web.UI;

namespace WebComponent
{
    
public class UserComponent : Control
    
{
                    
        
public UserComponent()
        

        }


        
public override void RenderControl(HtmlTextWriter writer)
        
{
            
//writer.Write(@"<script language='javascript'>alert('RenderControl');</script>");
            
//base.RenderControl(writer);
            
            
if (this.Visible)
            
{
                Render(writer);
            }

                
        }


        
protected override void Render(HtmlTextWriter writer)
        
{
            
//writer.Write(@"<script language='javascript'>alert('Render');</script>");
            
//base.Render(writer);
          
            RenderChildren(writer);

            
         }


        
protected override void RenderChildren(HtmlTextWriter writer)
        
{
            
//writer.Write(@"<script language='javascript'>alert('RenderChildren');</script>");
            
//base.RenderChildren(writer);

            
foreach (Control c in this.Controls)
            
{
                c.RenderControl(writer);
            }


        }

    
    }

}