我有一个 ASP.Net 页面,其中包含多个实现 IPostBackEventHandler 接口的控件。代码的简化版本如下:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Custom Control
MyTextBox mytxt = new MyTextBox();
mytxt.ID = "mytxt";
mytxt.TextChange += mytxt_TextChange;
this.Form.Controls.Add(mytxt);
//Custom Control
MyButton mybtn = new MyButton();
mybtn.ID = "mybtn";
mybtn.Click += mybtn_Click;
this.Form.Controls.Add(mybtn);
}
void mybtn_Click(object sender, EventArgs e)
{
Response.Write("mybtn_Click");
}
void mytxt_TextChange(object sender, EventArgs e)
{
Response.Write("mytxt_TextChange");
}
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class MyTextBox : Control, IPostBackEventHandler
{
public event EventHandler TextChange;
protected virtual void OnTextChange(EventArgs e)
{
if (TextChange != null)
{
TextChange(this, e);
}
}
public void RaisePostBackEvent(string eventArgument)
{
OnTextChange(new EventArgs());
}
protected override void Render(HtmlTextWriter output)
{
output.Write("<input type='text' id='" + ID + "' name='" + ID + "' onchange='__doPostBack('" + ID + "','')' />");
}
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class MyButton : Control, IPostBackEventHandler
{
public event EventHandler Click;
protected virtual void OnClick(EventArgs e)
{
if (Click != null)
{
Click(this, e);
}
}
public void RaisePostBackEvent(string eventArgument)
{
OnClick(new EventArgs());
}
protected override void Render(HtmlTextWriter output)
{
output.Write("<input type='button' id='" + ID + "' name='" + ID + "' value='Click Me' onclick='__doPostBack('" + ID + "','')' />");
}
}
有 2 个自定义控件 - MyTextBox 和 MyButton 实现 IPostBackEventHandler 接口。MyTextBox 具有 TextChange 事件,而 MyButton 具有 Click 事件。
如果我在页面上只保留一个控件(MyTextBox 或 MyButton) - 事件触发属性。但是对于页面上的两个控件,即使在单击 MyButton 之后,MyTextBox TextChange 事件也会被触发。当 MyTextBox 在页面上时,不会触发 MyButton Click 事件。
在将其发布到此处之前,我已经尝试了多种方法。在此先感谢您的帮助。