开发者

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 N开发者_高级运维avigationWindow_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, 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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜