代码之家  ›  专栏  ›  技术社区  ›  Rich

如何知道UserControl何时完成触发事件?

  •  2
  • Rich  · 技术社区  · 16 年前

    我们有一个UserControl来处理用户取消,这在一些地方使用。它有两个输入字段和一个提交按钮。当他们提交时,用户的状态会被更新,其他一些事情也会完成,并显示一条反馈消息。

    在包含控件的其中一个页面上,在用户通过UserControl成功取消提交后,我们需要以某种方式通知该页面,以便该页面可以调用其方法之一并更新其显示[在本例中,是用户的状态,该状态正在参与,现在已取消]。

    我们如何把这些联系起来?我会猜测一些涉及代理和事件处理程序的事情,但对他们没有太多经验,所以不知道我是否会走上死胡同。。。

    一个非常棘手的解决方案是,UserControl导致重新定向,然后让页面监视会话或查询字符串参数等,但仅仅键入它就让我不寒而栗,因此这是最后的手段。

    如果需要更多信息,请询问,我会提供。

    4 回复  |  直到 16 年前
        1
  •  2
  •   djdd87    16 年前

    这应该很容易。将委托事件添加到UserControl,如下所示:

    public event EventHandler UserCancelled;
    

    if (this.UserCancelled!= null)
    {
       this.UserCancelled(this, new EventArgs());
    }
    

    然后,只需向用户控件的aspx标记上的事件添加一个处理程序:

    OnUserCancelled="UserControl1_UserCancelled"
    

    最后,向页面添加一个处理程序:

    protected void UserControl1_UserCancelled(object sender, EventArgs e)
    {
        // Your code
    }
    
        2
  •  1
  •   Kyle Chafin    16 年前

    public delegate void CancelledUserHandler();
    
    public partial class UserCancellationControl : System.Web.UI.UserControl
    {
        public event CancelledUserHandler UserCancelled;
    
        protected void CancelButtonClicked(object sender, EventArgs e)
        {
            // process the user's cancellation
    
            // fire off an event notifying listeners that a user was cancelled
            if (UserCancelled != null)
            {
                UserCancelled();
            }
        } 
    }
    
    public partial class MyPage : System.Web.UI.Page
    {
        protected UserCancellationControl myControl;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            // hook up the ProcessCancelledUser method on this page
            // to respond to cancellation events from the user control
            myControl.UserCancelled += ProcessCancelledUser;
        }
    
        protected void ProcessCancelledUser()
        {
            // update the users status on the page
        }
    }
    
        3
  •  0
  •   JaredPar    16 年前

    最简单的方法是在UserControl上创建一个事件来表示取消已经发生。在原始表单中为其添加处理程序,并在触发时更新显示。

        4
  •  -1
  •   DRapp    16 年前

    如果表单是您自己设计的类,例如

    public class MyForm : Form
    {
       public void MyCustomRefresh()
       {
       }
    }
    

    然后,在您的自定义用户控件中,我假设它在多个窗体上使用,以允许记录您描述的cancel。。。然后,在任何事件/按钮的代码末尾,您可以执行以下操作

    ((MyForm)this.FindForm()).MyCustomRefresh()
    

    因此,您可以使用“this.FindForm()”来获取表单,输入cast到您的自定义表单定义,您知道它有这样的“MyCustomRefresh()”方法,并直接调用它。不需要代表。