1. 引言
\n
前几次任务里我们开发的星级控件只能显示一个条目的评分,在现实生活中,经常会遇到需要向用户展示一系列数据的评分状态,例如下图所示:
\n
\n
本次任务里,我们将一起开发这样一个控件。
\n
2. 分析
\n
通过上图可以看到,该自定义控件是一系列数据评分等级的列表,很显然需要作为一个数据绑定控件来实现才可以灵活的显示多条数据,并且在该列表上方显示了标题和当前的日期,为了允许用户灵活的定义标题和二级标题(当前日期),有必要引入模版的概念,由用户编辑模版,最终按照模版内容显示。如此看来再使用DataBoundControl作为自定义控件的基类就不太适合了,因为我们要在该控件中包含多个子控件,那么我们应该选择哪个类作为基类?
\n
回忆一下第六天的任务中数据绑定控件的类关系图,其中有一个继承自DataBoudControl类的CompositeDataBoundControl类,该类是.NET Framework 2.0中新增的一个类,用作绑定到数据源中的数据服务器控件的基类,该定义定义如下:
public abstract class CompositeDataBoundControl : DataBoundControl, INamingContainer
\n
可以看到,该在只是在继承DataBoundControl类的基础上实现了INamingContainer,这意味着该类所包含的子控件都会生成唯一的ID属性。
\n
但是CompositeDataBoundControl是如何实现数据绑定的呢,换句话说,如果某一个页面包含了一个复杂数据绑定控件,在某一个服务器端控件引起回发后,如何确保数据绑定控件能正确的被填充呢?按照设计,ASP.NET中的数据绑定组合控件只能从数据绑定中获取数据,并且不会缓存任何绑定的数据,因此,需要提供一个特殊的方法来处理回发事件。
\n
再次回顾一下DataBoundControl这个类,我们来分析一下数据是如何被显示出来的。在DataBoundControl类上重载了BaseDataBoundControl类上定义的PerformSelect方法,该方法如下所示:
protected override void PerformSelect()
\n{
\n if (this.DataSourceID.Length == 0)
\n {
\n this.OnDataBinding(EventArgs.Empty);
\n }
\n DataSourceView data = this.GetData();
\n this._arguments = this.CreateDataSourceSelectArguments();
\n this._ignoreDataSourceViewChanged = true;
\n base.RequiresDataBinding = false;
\n this.MarkAsDataBound();
\n data.Select(this._arguments, new
\n DataSourceViewSelectCallback(this.OnDataSourceViewSelectCallback));
\n}
\n
该方法的关键在于不论数据源是通过DataSource属性指定还是通过DataSourceID属性指定,最终都是通过数据源视图对象(DataSourceView)来获取数据,在获取数据源视图之后调用了该对象的Select方法,以获取可枚举的数据集合(不论数据源是以何种方式提供),该方法还接收多个输入参数和回调函数。
\n
到现在为止,我们已经可以通过为控件设置数据源数据并且通过数据源视图找到要读取的数据,那么接下来要考虑的是,如果访问这个可绑定的数据集合以将其显示到页面上?
\n
答案是在数据源视图上处理Select语句操作结果的回调函数最后会调用一个可重载的受保护方法PerformDataBinding方法,该方法定义如下:
protected internal virtual void PerformDataBinding (
\n IEnumerable data
\n)
\n
PerformDataBinding方法接收一个IEnumerable类型的对象以访问返回的数据列表,我们可以利用该对象迭代访问数据并根据需要创建控件的内部结构最终呈现给用户。
\n
对于数据绑定组合控件,和独自处理数据绑定的控件不同,它不将数据保存到视图中,而是交由各个子控件处理,此时,就不能通过简单的重写CreateChildControls方法实现了,通过.NET Reflection工具观察CompositeDataBindControl类上该方法的实现:
protected internal override void CreateChildControls()
\n{
\n this.Controls.Clear();
\n object obj2 = this.ViewState["_!ItemCount"];
\n if ((obj2 == null) && base.RequiresDataBinding)
\n {
\n this.EnsureDataBound();
\n }
\n if ((obj2 != null) && (((int)obj2) != -1))
\n {
\n DummyDataSource dataSource = new DummyDataSource((int)obj2);
\n this.CreateChildControls(dataSource, false);
\n base.ClearChildViewState();
\n }
\n}
\n
CreateChildControls方法有两种工作模式:绑定模式和非绑定模式。
\n
在绑定模式下,将会正常创建控件树,具体来说会在执行PerformDataBinding方法中调用重载的CreateChildControls方法,以手动的实现数据控件层次的创建;
protected internal override void PerformDataBinding(IEnumerable data)而在非绑定模式中,将从CreateChildControls方法中调用带有两个参数的重载:
\n{
\n base.PerformDataBinding(data);
\n this.Controls.Clear();
\n base.ClearChildViewState();
\n this.TrackViewState();
\n int num = this.CreateChildControls(data, true);
\n base.ChildControlsCreated = true;
\n this.ViewState["_!ItemCount"] = num;
\n}
DummyDataSource dataSource = new DummyDataSource((int) obj2);
\nthis.CreateChildControls(dataSource, false);
\nbase.ClearChildViewState();
\n
在这种情况下,传递给CreateChildControls方法的第二个参数为false,这表示不会向控件层次添加任何数据。ASP.NET回发机制确保每一个子控件正确的从视图中恢复自己的值。
\n
接下来观察在CompositeDataBindControl类上定义的CreateChildControls方法的重载:
protected abstract int CreateChildControls (
\n IEnumerable dataSource,
\n bool dataBinding
\n)
\n
该方法的参数说明如下:
\n
属性 | 描述 |
---|---|
\n Attribute | 在最终的标记中,该属性永久存储为一个已编码的HTML特性 |
EncodedInnerDefaultProperty | 该属性存储为该控件的内部文本。该属性的值是编码的HTML,只能将字符串赋给该属性 |
InnerDefaultProperty | 永久存储为控件中的内部文本的属性并且是元素的默认属性,只有一个属性能够指定为默认属性 |
InnerProperty | 该属性永久存储为控件中的一个嵌入标记,这是使用模版和风格的复杂对象常用的一个属性。 |
\n
模版属性示例如下所示:
private ITemplate _titleTemplate;
\n[PersistenceMode(PersistenceMode.InnerProperty)]
\n[TemplateContainer(typeof(TitleTemplateContainer))]
\npublic ITemplate TitleTemplate
\n{
\n get
\n {
\n return _titleTemplate;
\n }
\n set
\n {
\n _titleTemplate = value;
\n }
\n}
\n
3. 实现
\n
3.1 在解决方案ControlLibrary类库中创建BarChartItem类用于表示控件项:
using System;
\nusing System.Collections.ObjectModel;
\nusing System.Web.UI;
\nusing System.Web.UI.WebControls;\npublic class BarChartItem:TableRow
\n
\n{
\n public BarChartItem(BarChartItemType itemType)
\n {
\n ItemType = itemType;
\n }public BarChartItemType ItemType
\n
\n {
\n get;
\n set;
\n }public object DataItem
\n {
\n get;
\n set;
\n }
\n}
\n
3.2 在BarChartItem类中使用了BarChartItemType枚举以标识当前项的类型(类似于GridView中的标题、交替行等),编写该枚举实现:
public enum BarChartItemType
\n{
\n Title, //标题
\n SubTitle, //二级标题
\n Item, //数据项
\n Footer //页脚
\n}
\n
3.3 定义该控件项的集合类BarChartItemCollection:
public class BarChartItemCollection : Collection<BarChartItem>3.4 为了能够在创建项和绑定数据后暴露出相应的事件中使用户能够访问数据项信息,编写自定义事件参数类:
\n{
\n}
public class BarChartItemEventArgs : EventArgs
\n{
\n private BarChartItem _item;\npublic BarChartItemEventArgs(BarChartItem item)
\n
\n {
\n _item = item;
\n }public BarChartItem Item
\n {
\n get
\n {
\n return _item;
\n }
\n }
\n}
\n
3.5 定义模版容器类
public class TitleTemplateContainer : WebControl, INamingContainer
\n{
\n private BarChart _parent;\npublic TitleTemplateContainer(BarChart parent)
\n
\n {
\n _parent = parent;
\n }public string Title
\n
\n {
\n get
\n {
\n return _parent.Title;
\n }
\n }public string SubTitle
\n
\n {
\n get
\n {
\n return _parent.SubTitle;
\n }
\n }public BarChart BarChart
\n {
\n get
\n {
\n return _parent;
\n }
\n }
\n}
\n
3.6 在ControlLibrary类库中创建BarChar类并定义私有变量,该类继承自CompositeDataBoundControl类:
public class BarChart : CompositeDataBoundControl
\n{
\n public event EventHandler<BarChartItemEventArgs> BarChartItemCreated;
\n public event EventHandler<BarChartItemEventArgs> BarChartItemDataBound;
\n private BarChartItemCollection _items;
\n private ITemplate _titleTemplate;
\n private TitleTemplateContainer _titleTemplateContainer;
\n private TableItemStyle _titleStyle;
\n private TableItemStyle _subtitleStyle;
\n private TableItemStyle _labelStyle;
\n}
\n
3.7 定义相关属性:
public string DataTextField
\n{
\n get
\n {
\n object o = ViewState["DataTextField"];
\n return o == null ? string.Empty : (string)o;
\n }
\n set
\n {
\n ViewState["DataTextField"] = value;
\n }
\n}\npublic string DataValueField
\n
\n{
\n get
\n {
\n object o = ViewState["DataValueField"];
\n return o == null ? string.Empty : (string)o;
\n }
\n set
\n {
\n ViewState["DataValueField"] = value;
\n }
\n}public BarChartItemCollection Items
\n
\n{
\n get
\n {
\n if (_items == null)
\n {
\n _items = new BarChartItemCollection();
\n }
\n return _items;
\n }
\n}[Browsable(false)]
\n
\n[PersistenceMode(PersistenceMode.InnerProperty)]
\n[TemplateContainer(typeof(TitleTemplateContainer))]
\npublic ITemplate TitleTemplate
\n{
\n get
\n {
\n return _titleTemplate;
\n }
\n set
\n {
\n _titleTemplate = value;
\n }
\n}public string Title
\n
\n{
\n get
\n {
\n object o = ViewState["Title"];
\n return o == null ? string.Empty : (string)o;
\n }
\n set
\n {
\n ViewState["Title"] = value;
\n }
\n}public string SubTitle
\n
\n{
\n get
\n {
\n object o = ViewState["SubTitle"];
\n return o == null ? string.Empty : (string)o;
\n }
\n set
\n {
\n ViewState["SubTitle"] = value;
\n }
\n}[PersistenceMode(PersistenceMode.InnerProperty)]
\n
\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
\n[NotifyParentProperty(true)]
\n[Description("标题样式")]
\npublic virtual TableItemStyle TitleStyle
\n{
\n get
\n {
\n if (_titleStyle == null)
\n {
\n _titleStyle = new TableItemStyle();
\n }if (IsTrackingViewState)
\n
\n ((IStateManager)_titleStyle).TrackViewState();return _titleStyle;
\n
\n }
\n}[PersistenceMode(PersistenceMode.InnerProperty)]
\n
\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
\n[NotifyParentProperty(true)]
\n[Description("二级标题样式")]
\npublic virtual TableItemStyle SubTitleStyle
\n{
\n get
\n {
\n if (_subtitleStyle == null)
\n {
\n _subtitleStyle = new TableItemStyle();
\n }if (IsTrackingViewState)
\n
\n ((IStateManager)_subtitleStyle).TrackViewState();return _subtitleStyle;
\n
\n }
\n}[PersistenceMode(PersistenceMode.InnerProperty)]
\n
\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
\n[NotifyParentProperty(true)]
\n[Description("标签样式")]
\npublic virtual TableItemStyle LabelStyle
\n{
\n get
\n {
\n if (_labelStyle == null)
\n {
\n _labelStyle = new TableItemStyle();
\n // Can initialize the style HERE
\n }if (IsTrackingViewState)
\n
\n ((IStateManager)_labelStyle).TrackViewState();return _labelStyle;
\n }
\n}
\n
3.8 定义事件响应方法:
protected virtual void OnBarChartCreated(BarChartItemEventArgs e)
\n{
\n if (BarChartItemCreated != null)
\n BarChartItemCreated(this, e);
\n}\nprotected virtual void OnBarChartDataBound(BarChartItemEventArgs e)
\n{
\n if (BarChartItemDataBound != null)
\n BarChartItemDataBound(this, e);
\n}
\n
3.9 编写创建子控件层次方法:
protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
\n{
\n return CreateControlHierarchy(dataSource, dataBinding);
\n}\nprivate int CreateControlHierarchy(IEnumerable dataSource, bool dataBinding)
\n
\n{
\n if (dataSource == null)
\n {
\n RenderEmptyControl();
\n return 0;
\n }Table t = new Table();
\n
\n Controls.Add(t);//创建标题
\n
\n CreateTitle(t);//创建二级标题
\n
\n CreateSubTitle(t);//创建数据项
\n
\n int totalItems = CreateAllItems(t, dataSource, dataBinding);return totalItems;
\n}
\n
3.10 编写创建控件方法:
private void RenderEmptyControl()
\n{
\n LiteralControl lbl = new LiteralControl(“??????”);
\n Controls.Add(lbl);
\n}\nprivate void CreateTitle(Table t)
\n
\n{
\n BarChartItem item = new BarChartItem(BarChartItemType.Title);
\n t.Rows.Add(item);TableCell cell = new TableCell();
\n
\n item.Cells.Add(cell);cell.ColumnSpan = 2;
\nif (TitleTemplate != null)
\n
\n {
\n _titleTemplateContainer = new TitleTemplateContainer(this);
\n TitleTemplate.InstantiateIn(_titleTemplateContainer);
\n cell.Controls.Add(_titleTemplateContainer);
\n }
\n else
\n {
\n cell.Text = Title;
\n }item.DataBind();
\n
\n}private void CreateSubTitle(Table t)
\n
\n{
\n BarChartItem item = new BarChartItem(BarChartItemType.SubTitle);t.Rows.Add(item);
\n
\n TableCell cell = new TableCell();
\n item.Cells.Add(cell);cell.ColumnSpan = 2;
\n
\n cell.Text = SubTitle;
\n}private int CreateAllItems(Table t, IEnumerable data, bool useDataSource)
\n
\n{
\n int itemCount = 0;Items.Clear();
\nforeach (object o in data)
\n
\n {
\n BarChartItemType itemType = BarChartItemType.Item;
\n BarChartItem item = CreateBarChartItem(t, itemType, o, useDataSource);_items.Add(item);
\nitemCount++;
\n
\n }return itemCount;
\n
\n}private BarChartItem CreateBarChartItem(Table t, BarChartItemType itemType, object dataItem, bool useDataSource)
\n
\n{
\n BarChartItem item = new BarChartItem(itemType);TableCell labelCell = CreateLabelCell(item);
\n
\n TableCell valueCell = CreateScoreCell(item);BarChartItemEventArgs argsCreated = new BarChartItemEventArgs(item);
\nOnBarChartCreated(argsCreated);
\nt.Rows.Add(item);
\nif (useDataSource)
\n
\n {
\n item.DataItem = dataItem;BindLabelCell(labelCell, dataItem);
\n
\n BindValueCell(valueCell, dataItem);BarChartItemEventArgs argsData = new BarChartItemEventArgs(item);
\nOnBarChartDataBound(argsData);
\n
\n }return item;
\n
\n}private TableCell CreateLabelCell(BarChartItem item)
\n
\n{
\n TableCell cell = new TableCell();item.Cells.Add(cell);
\nreturn cell;
\n
\n}private TableCell CreateScoreCell(BarChartItem item)
\n
\n{
\n TableCell cell = new TableCell();
\n item.Cells.Add(cell);string starPath = Page.ClientScript.GetWebResourceUrl(this.GetType(), “ControlLibrary.Image.stars.gif”);
\nPanel panBg = new Panel();
\n
\n panBg.Style.Add(HtmlTextWriterStyle.Width, “80px”);
\n panBg.Style.Add(HtmlTextWriterStyle.Height, “16px”);
\n panBg.Style.Add(HtmlTextWriterStyle.TextAlign, “left”);
\n panBg.Style.Add(HtmlTextWriterStyle.Overflow, “hidden”);
\n panBg.Style.Add(HtmlTextWriterStyle.BackgroundImage, starPath);
\n panBg.Style.Add(“background-position”, “0px -32px”);
\n panBg.Style.Add(“background-repeat”, “repeat-x”);cell.Controls.Add(panBg);
\nPanel panCur = new Panel();
\npanCur.Style.Add(HtmlTextWriterStyle.Height, “16px”);
\n
\n panCur.Style.Add(HtmlTextWriterStyle.BackgroundImage, starPath);
\n panCur.Style.Add(“background-position”, “0px 0px”);
\n panCur.Style.Add(“background-repeat”, “repeat-x”);panBg.Controls.Add(panCur);
\nreturn cell;
\n
\n}private void BindLabelCell(TableCell cell, object dataItem)
\n
\n{
\n if (!string.IsNullOrEmpty(DataTextField))
\n {
\n string txt = Convert.ToString(DataBinder.GetPropertyValue(dataItem, DataTextField));
\n cell.Text = txt;
\n }
\n}/// <summary>
\n
\n/// ????????????
\n/// </summary>
\n/// <param name=”cell”></param>
\n/// <param name=”dataItem”></param>
\nprivate void BindValueCell(TableCell cell, object dataItem)
\n{
\n Panel panCur = (Panel)cell.Controls[0].Controls[0];
\n object o = null;if (!String.IsNullOrEmpty(DataValueField))
\n
\n o = DataBinder.GetPropertyValue(dataItem, DataValueField);
\n else
\n return;
\n int score = Convert.ToInt32(o);string width = score * 16 + “px”;
\n
\n panCur.Style.Add(HtmlTextWriterStyle.Width, width);
\n}protected override void Render(HtmlTextWriter writer)
\n
\n{
\n PrepareControlForRender();
\n base.Render(writer);
\n}public void PrepareControlForRender()
\n
\n{
\n if (Controls.Count != 1)
\n return;Table t = (Table)Controls[0];
\n
\n t.CopyBaseAttributes(this);
\n if (ControlStyleCreated)
\n t.ApplyStyle(ControlStyle);t.Rows[0].Cells[0].MergeStyle(TitleStyle);
\nt.Rows[1].Cells[0].MergeStyle(SubTitleStyle);
\n// Apply style to the labels that render team names
\n for (int i = 2; i < Items.Count; i++)
\n {
\n // Style team labels
\n t.Rows[i].Cells[0].ApplyStyle(LabelStyle);
\n }
\n}
\n
3.10 在页面中声明并定义自定义控件,预览结果。
<cc:BarChart ID=”bar” runat=”server” Font-Size=”12px” Title=”????????”>
\n <TitleTemplate>
\n <%# Container.Title %>
\n <small>(<%# DateTime.Now.ToString() %>)</small>
\n </TitleTemplate>
\n</cc:BarChart>
\n
3.11 编写后置代码,预览结果:
protected void Page_Load(object sender, EventArgs e)
\n{
\n if (!IsPostBack)
\n this.BindData();
\n}\nprivate void BindData()
\n
\n{
\n DataTable table = new DataTable();DataColumn col = new DataColumn(“Comment”, typeof(string));
\n
\n table.Columns.Add(col);
\n col = new DataColumn(“Score”, typeof(int));
\n table.Columns.Add(col);Random ran=new Random();
\nfor (int i = 0; i < 10; i++)
\n
\n {
\n DataRow row = table.NewRow();
\n int num= ran.Next(0, 6);
\n row[0] = “数据 “+i+” , “+num+” 星”;row[1] = num;
\ntable.Rows.Add(row);
\n
\n }table.AcceptChanges();
\nbar.DataSource = table;
\n
\n bar.DataTextField = “Comment”;
\n bar.DataValueField = “Score”;bar.DataBind();
\n}
\n
4. 总结
\n
复杂绑据绑定控件可以通过扩展CompositeDataBindControl类实现,该类有一个特殊的CreateChildControls方法实现数据的绑定和恢复,在下一次任务里,我们将尝试扩展DataList和GridView以实现自定义分页控件。
\n\n