以下是我的测试代码:
APP_Code/ucInterface.cs
/* APP_Code/ucInterface.cs */ /// <summary> /// Summary description for ucInterface /// </summary> public interface ucInterface { int id { get; set; } }
WebUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %> <asp:Label ID="Label1" runat="server" Text='<%# id %>'></asp:Label>
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" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div id="div1" runat="server" /> </form> </body> </html>
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的中属性。 } }