【问题标题】:How to know when a UserControl has finished firing an Event?如何知道 UserControl 何时完成触发事件?
【发布时间】:2009-11-05 16:31:29
【问题描述】:

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

在包含控件的页面之一上,在用户通过 UserControl 成功取消提交后,我们需要以某种方式通知页面,以便它可以调用其中一个方法并更新其显示 [在这种情况下,用户状态,以前参加过,现在取消了]。

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

一个非常 hacky 的解决方案是 UserControl 导致重定向,然后让页面监控会话或查询字符串参数等,但只是输入它就让我颤抖,所以必须非常不得已。

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

【问题讨论】:

  • 既然你说“字符串参数”和“页面”,我假设你在谈论 webforms 而不是 winforms。
  • 我重新标记到 ASP.Net 正如你提到的重定向到页面。如果我错了,这是winforms,请随时纠正我。
  • 是的,这适用于网络,而不是桌面。
  • 看看我的答案,应该有你需要的一切:)。
  • +1 表示结构良好且内容丰富的问题​​。

标签: c# asp.net user-controls event-handling delegates


【解决方案1】:

这应该很容易。向您的 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
}

【讨论】:

  • 只添加不编辑,如果您总是使用事件,则不需要放入“if (this.UserCancelled!= null)”部分。如果您并不总是想要捕获事件,那么确保委托不为空可以防止它导致错误。
【解决方案2】:

我认为你的直觉是正确的。您可以通过定义自定义事件和委托来解决此问题。应该这样做:

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
    }
}

【讨论】:

  • 这也是一个很棒的回复,但被 GenericTypeTea 的回答打败了。
  • 嘿,我很享受看我和凯尔之间的名誉乒乓球。最后感谢您接受我的回答。
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    如果你的表单是你自己设计的类比如

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

    然后,在您的自定义用户控件中,我假设它用于多种表单以允许记录您所描述的取消...然后,在您的任何事件/按钮的代码末尾,您可以执行类似

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

    因此,您可以使用“this.FindForm()”来获取表单,将类型转换为您知道具有此类“MyCustomRefresh()”方法的自定义表单定义并直接调用它。无需委托。

    【讨论】:

    • 是的,很抱歉造成混乱。
    猜你喜欢
    • 2020-01-03
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 2013-10-03
    • 1970-01-01
    • 2018-10-08
    相关资源
    最近更新 更多