1

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.

Marc
  • 9,012
  • 13
  • 57
  • 72
  • You mean that the `Page` should be notified when the application decides to close? What could it do that you can't already do from the `Window` that hosts the page? – Jon Apr 05 '11 at 13:17
  • @Jon: As an example the Page may have to save the state of some UI elements to settings. The Window doesn't have access to these UI elements. – Marc Apr 05 '11 at 13:28

2 Answers2

2

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
1

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;
}
RQDQ
  • 15,461
  • 2
  • 32
  • 59
  • [+1] I came up with exactly this solution for now, though my method is called CancelApplicationClosing() :-) – Marc Apr 05 '11 at 14:27