Search code examples
c#wpfnavigationwindow

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.


Solution

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