ASP.NET控件开发基础(17)

http://tech.ddvip.com   2007年09月02日    社区交流

内容摘要:ASP.NET控件开发基础

  原因很明显,为了减少对数据源的访问,所以我们平时操作数据的时候,必须重新执行DataBind方法,原因就在此

  好了,到了这里差不多主要的事情我们已经完成.接着把剩下的也完成

  3.呈现

  又到了Render方法这里了

  此方法体只要执行了PrepareControlHierarchy方法,不同的方法做不同的事情,CreateControlHierarchy方法根据索引值指定了不同的项,PrepareControlHierarchy则为不同项呈现不同的样式效果

    //为不同类型项加载样式
    private void PrepareControlHierarchy()
    {
      if (HasControls() == false)
      {
        return;
      }
  
      Debug.Assert(Controls[0] is Table);
      Table table = (Table)Controls[0];
  
      table.CopyBaseAttributes(this);
      if (ControlStyleCreated)
      {
        table.ApplyStyle(ControlStyle);
      }
  
      // The composite alternating item style; do just one
      // merge style on the actual item.
      Style altItemStyle = null;
      if (alternatingItemStyle != null)
      {
        altItemStyle = new TableItemStyle();
        altItemStyle.CopyFrom(itemStyle);
        altItemStyle.CopyFrom(alternatingItemStyle);
      }
      else
      {
        altItemStyle = itemStyle;
      }
  
      int rowCount = table.Rows.Count;
      for (int i = 0; i < rowCount; i++)
      {
        TemplatedListItem item = (TemplatedListItem)table.Rows[i];
        Style compositeStyle = null;
        //根据不同项加载不同样式
        switch (item.ItemType)
        {
          case ListItemType.Item:
            compositeStyle = itemStyle;
            break;
  
          case ListItemType.AlternatingItem:
            compositeStyle = altItemStyle;
            break;
  
          case ListItemType.SelectedItem:
            {
              compositeStyle = new TableItemStyle();
  
              if (item.ItemIndex % 2 != 0)
                compositeStyle.CopyFrom(altItemStyle);
              else
                compositeStyle.CopyFrom(itemStyle);
              compositeStyle.CopyFrom(selectedItemStyle);
            }
            break;
        }
  
        if (compositeStyle != null)
        {
          item.MergeStyle(compositeStyle);
        }
      }
    }
  
    //控件呈现
    protected override void Render(HtmlTextWriter writer)
    {
      // Apply styles to the control hierarchy
      // and then render it out.
  
      // Apply styles during render phase, so the user can change styles
      // after calling DataBind without the property changes ending
      // up in view state.
      PrepareControlHierarchy();
  
      RenderContents(writer);
    }

  终于差不多了,经过这么多步骤,我们终于完成了,让我们来使用控件,看一下效果

  ASP.NET控件开发基础(17)

  又完成一个并不完美的控件,本来还该继续下去的,怕篇幅太大,到这里还没结束,只是刚开始,下次我们继续

责编:豆豆技术应用

正在加载评论...