以下是我的测试代码:
APP_Code/ucInterface.cs/* APP_Code/ucInterface.cs */////// Summary description for ucInterface/// public interface ucInterface{ int id { get; set; }}
WebUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
WebUserControl.ascx.cs
using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class WebUserControl : System.Web.UI.UserControl, ucInterface{ private int _id = 2;//有一个初始值2. protected void Page_Load(object sender, EventArgs e) { Label1.DataBind(); } public int id { get { return ViewState["__id"] == null ? this._id : (int)ViewState["__id"]; } set { this._id = value; ViewState["__id"] = value; } }}
default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>Untitled Page
default.aspx.cs
using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Control c = Page.LoadControl("WebUserControl.ascx"); c.ID = "uc1"; div1.Controls.Add(c); } ucInterface uc1 = Page.FindControl("uc1") as ucInterface;//转化到app_code中的 ucInterface 接口 uc1.id = 234324324;//OK, 重新设置id的值(它的初始值我乱写的,是2) //Page.DataBind();//不用再调用数据绑定也行。页面是显示:234324324而不是2,注释掉上面一句页面就会显示2了。说明我们成功的使用了usercontrol的中属性。 }}
posted on 2013-09-04 15:28 阅读( ...) 评论( ...)