通过继承扩展功能

更新:2007 年 11 月

除了创建用户控件外,还可以使用继承来扩展 ASP.NET 移动网页的功能。如果您创建从现有 ASP.NET 移动控件类继承的类,则可以通过重写现有成员或通过为类创建新属性、方法和事件来添加功能。

通过继承创建类

下面的代码示例演示一个名为 CarList 的新类,该类从 List 移动控件继承,并专用于呈现车辆信息。CarList 类封装绑定到一组 Car 对象所需的信息。

using System.Web.UI.MobileControls;

namespace myCompany.MobileControls
{
    class CarList : List
    {
        // Override OnInit, and set the DataValueField property
        // to the correct property of a Car object to use as the 
        // value of each list item.
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.DataValueField = "id";
        }
    
        // Override OnItemDataBind, and set the list item display 
        // text to a rich expression, containing the year, make, 
        // and model of the car.
        protected override void OnItemDataBind(ListDataBindEventArgs e)
        {
            base.OnItemDataBind(e);

            CarInfo car = (Car)e.DataItem;
            e.ListItem.Text = 
              String.Format("{0}{1}{2}", car.Year, car.Make, car.Model);
        }
    }
}

有关通过继承扩展控件功能的更详细的示例,请参见 ASP.NET 移动快速入门教程。

部署新类

若要使用此示例类,请将该类编译为一个程序集,并将它放入应用程序的 Bin 文件夹。下面的示例演示如何注册一个名为 MyCompany.CarList.dll 的程序集。请使用 @ Register 指令在页上注册程序集,同时指定一个自定义标记。

<%-- Register the myCompany.MobileControls namespace. --%>
<%@ Register TagPrefix="car" Namespace="myCompany.MobileControls" 
    Assembly="myCompany.CarList" %>
    // More code.
    <%-- Control declaration --%>
    <car:CarList id="myCarList" runat="server" />

如果继承的控件不修改父类的呈现功能,则不需要为类编写适配器。在前面的示例中,因为每个 CarList 控件也是 List 对象,所以自动使用分配给当前浏览器的 List 控件的适配器(例如 HtmlListAdapter)。但是,如果您想要为特定设备提供专用的 CarList 控件的呈现,则可以编写一个适配器并在 Web.config 文件中注册映射。

请参见

其他资源

添加新的设备适配器和设备支持

创建自定义移动控件