用户控件如何控制ASPX页面的控件
问题来自论坛http://topic.csdn.net/u/20120415/17/3f264265-b25c-4db8-a192-520e8a60e4c1.html?85396
问题分析,aspx页面的控件需要控制显示与否,就如同象是一个小电灯,为了不让它通电之后常亮。因此需要一个开关才能控制到它。什么样的开关它管不了那么多,只要能控制开与关功能即可。
用户控件的Button,它可以实现开关功能。它可以控制电器的电路开与关。
接下来,两个电器是不同的对象,怎样让它们连接在一起。在程序中,可以使用Interface(接口)来实现。我们可以写一个叫开关接口ISwitchable。
ISwitchable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for ISwitchable
/// </summary>
namespace Insus.NET
{
public interface ISwitchable
{
void Switch(bool show);
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for ISwitchable
/// </summary>
namespace Insus.NET
{
public interface ISwitchable
{
void Switch(bool show);
}
}
是什么物件需要控制,也就是说什么电器需要安装开关,这里是aspx的控件需要控制显示与否。因此aspx.cs实现这个接口。
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class _Default : System.Web.UI.Page,ISwitchable
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Switch(bool show)
{
this.TextBox1.Visible = show;
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class _Default : System.Web.UI.Page,ISwitchable
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Switch(bool show)
{
this.TextBox1.Visible = show;
}
}
接下来,用户控件实现代码:
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class InsusWebUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ISwitchable sw = (ISwitchable)this.Page;
switch (btn.Text)
{
case "开":
btn.Text = "关";
sw.Switch(true);
break;
case "关":
btn.Text = "开";
sw.Switch(false);
break;
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class InsusWebUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ISwitchable sw = (ISwitchable)this.Page;
switch (btn.Text)
{
case "开":
btn.Text = "关";
sw.Switch(true);
break;
case "关":
btn.Text = "开";
sw.Switch(false);
break;
}
}
}
运行效果:
源程序(.NET3.5 + ASP.NET + C#):
http://download.cnblogs.com/insus/ASPDOTNET/uc_ctrl_ctrlOfpage.zip