简体   繁体   English

如果e.Cancel = true,我何时何地应该调用base.OnClosing(e)?

[英]If e.Cancel = true, when and where should I call base.OnClosing(e)?

protected override void OnClosing(CancelEventArgs e)
{
    base.OnClosing(e); // here?

    if (cancelCondition)
    {
        base.OnClosing(e); // or here?
        e.Cancel = true;
        base.OnClosing(e); // or here?
    }

    base.OnClosing(e); // or here?
}

I've tried a few different places, and it seems to work anywhere, just wondering if it matters. 我尝试了几个不同的地方,它似乎在任何地方工作,只是想知道它是否重要。 Does base.OnClosing(e); base.OnClosing(e); actually do anything? 实际上做了什么?

From MSDN : 来自MSDN

A type that derives from Window may override OnClosing. 从Window派生的类型可以重写OnClosing。 The overridden method must call OnClosing on the base class if Closing needs to be raised 如果需要引发Closing,则重写的方法必须在基类上调用OnClosing

In your case there seems to be no need to actually raise the Closing event, hence it doesn't matter if and where you call base.OnClosing . 在你的情况下,似乎没有必要实际提出Closing事件,因此无论你base.OnClosing何地调用base.OnClosing


You may however avoid to decide this in the first place if you do not override the OnClosing method, but simply add a Closing handler instead: 但是,如果您不重写OnClosing方法,则可以避免首先决定这一点,而只需添加一个Closing处理程序:

<Window ... Closing="Window_Closing">
    ...
</Window>

private void Window_Closing(object sender, CancelEventArgs e)
{
    if (cancelCondition)
    {
        e.Cancel = true;
    }
}

You should be overriding OnClosing if you want to change how the closing event is fired. 如果要更改触发事件的触发方式,则应该重写OnClosing

  1. If you want to execute code when the form is closing and have it run before any other Closing handlers, put your other code before base.OnClosing . 如果要在表单关闭时执行代码并使其在任何其他Closing处理程序之前运行,请将其他代码放在base.OnClosing之前。

  2. If you have code that you want to run after all other handlers have run, put that code after a call to base.OnClosing . 如果您希望在所有其他处理程序运行后运行代码,请在调用base.OnClosing之后输入该代码。

  3. If you want to only conditionally run all of the other handlers, put base.OnClosing inside of some sort of conditional block so that it is only called when you want the other handlers to be run. 如果您只想有条件地运行所有其他处理程序,请将base.OnClosing放在某种条件块中,以便仅在您希望运行其他处理程序时调用它。

There is no one right answer for where it belongs in all cases. 在所有情况下,没有一个正确的答案。 You should put it wherever you want "all of the other event handlers" to be run, relative to whatever code your adding. 您应该将它放在任何您想要“所有其他事件处理程序”的位置,相对于您添加的任何代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM