Marc
Marc

Reputation: 9282

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.

Upvotes: 1

Views: 2070

Answers (2)

RQDQ
RQDQ

Reputation: 15569

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

Upvotes: 1

Jon
Jon

Reputation: 437474

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, e.g. 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.

Upvotes: 2

Related Questions