微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 手动连接Page_PreInit事件,AutoEventWireup设置为false

如果AutoEventWireup属性设置为false,则需要手动连接事件.但是,我似乎无法触发Page_PreInit.我猜我可能会让连线发生得太晚(一旦我们已经超过Page_PreInit),但我不确定在哪里放置连线.

例如…

protected override void OnInit(EventArgs e)
{
    base.OnInit(e)
    PreInit += new EventHandler(Page_PreInit);
    Load += new EventHandler(Page_Load);
}

protected void Page_PreInit(object sender,EventArgs e)
{
    Response.Write("Page_PreInit event fired!<br>");  //this is never reached
}

protected void Page_Load(object sender,EventArgs e)
{
    Response.Write("Page_Load event fired!<br>");
}

上面的代码导致“Page_Load事件被触发!”正在显示,但没有来自Page_PreInit.我在连线之前和之后尝试了base.OnInit(e),但是没有效果.

显示的图表here表示OnInit方法实际上是在PreInit事件之后.考虑到这一点,我尝试重写OnPreInit并做同样的事情 – 没有效果.

MSDN文章here明确指出,如果将AutoEventWireup设置为false,则可以在重写的OnInit中连接事件.他们使用的例子是Page_Load,当然它就像对我一样,但它们没有解决这对于Page_PreInit事件似乎不起作用.

我的问题是:在AutoEventWireup设置为false的情况下,如何将Page_PreInit事件连接起来?

据我所知,MSDN page中列出了其他替代方法,例如使用页面的构造函数.我想具体了解他们如何使用OnInit建议.

解决方法

OnPreInit()方法的基本实现负责引发PreInit事件.由于您的覆盖在注册PreInit处理程序之前调用该实现,因此确实不会调用它.

注册处理程序后尝试调用基类的方法

protected override void OnPreInit(EventArgs e)
{
    PreInit += new EventHandler(Page_PreInit);
    Load += new EventHandler(Page_Load);

    // And only then:
    base.OnPreInit(e);
}

原文地址:https://www.jb51.cc/csharp/243599.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐