简体   繁体   中英

How to cancel WPF app closing from Page?

I'm using a WPF NavigationWindow and some Pages and would like to be able to know when the application is closing from a Page.
How can this be done without actively notifying the page from the NavigationWindow_Closing event handler?

I'm aware of the technique here , but unfortunately NavigationService_Navigating isn't called when the application is closed.

If I understand you correctly, your problem is how to get access to the content hosted inside the NavigationWindow . Knowing that the window itself is closing is trivial, eg there is the Closing event you can subscribe to.

To get the Page hosted in the NavigationWindow , you can use VisualTreeHelper to drill down into its descendants until you find the one and only WebBrowser control. You could code this manually, but there is good code like this ready to use on the net.

After you get the WebBrowser , it's trivially easy to get at the content with the WebBrowser.Document property.

One way to do this is have the pages involved support an interface such as:

public interface ICanClose
{
     bool CanClose();
}

Implement this interface at the page level:

public partial class Page1 : Page,  ICanClose
{
    public Page1()
    {
        InitializeComponent();
    }

    public bool CanClose()
    {
        return false;
    }
}

In the navigation window, check to see if the child is of ICanClose:

private void NavigationWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    ICanClose canClose = this.Content as ICanClose;

    if (canClose != null && !canClose.CanClose())
        e.Cancel = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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