拦截关闭窗口的最佳方法是什么?

时间:2015-07-09 14:12:07

标签: c# wpf

我正在寻找拦截软件窗口关闭的最佳方法。例如,我想拦截一个名为“settings”的表单的闭包,而不是MainWindow。程序的vb.net非常简单,我只需要调用它的结束事件,但是使用WPF我无法理解为什么没有捕获这个事件,因此,里面的代码没有被执行。

3 个答案:

答案 0 :(得分:3)

在表单中,您要拦截结束时间:

    protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
    {
        if(dontClose)
        {
            e.Cancel = true;
        }
        base.OnClosing(e);
    }

将dontClose替换为不关闭的条件。

答案 1 :(得分:0)

在XAML后面的cs文件中,添加:

    // Constructor
    public SettingsWindow()
    {
        InitializeComponent();

        Closing += SettingsWindow_Closing; // Subscribe to window closing event.
    }

    // Window closing event handler.
    private void SettingsWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        // Add method you want to run on close here.
    }

答案 2 :(得分:0)

如果您有视图模型,也可以从视图模型中访问它。喜欢这个

Application.Current.MainWindow.Closing += (s, e) =>{ your code comes here};