System.InvalidOperationException:无法设置可见性

时间:2015-09-06 08:51:41

标签: c# .net wpf

我创建了一个窗口,只有在外部单击时才能关闭该窗口。代码在这里工作得非常好:

 protected override void OnDeactivated(EventArgs e)
 {
     try
     {
         base.OnDeactivated(e);
         Close();
     }
     catch (Exception ex) { Console.WriteLine(ex.ToString()); }
 }

当窗口关闭时,唯一的问题就出现了,例如alt + f4,特别是这个例外:

  

您无法将Visibility设置为Visible或调用Show,ShowDialog,Close WindowInteropHelper.EnsureHandle或在关闭窗口时。

我怎样才能确保避免它?其实我用Try / Catch管理了这个例外..

1 个答案:

答案 0 :(得分:2)

在窗口引发Deactivated事件之前,会发生Closing事件(但显然,只有在用户有意关闭窗口时,例如按Alt+F4)。这意味着您可以在窗口的Closing事件处理程序中设置一个标志,指示窗口当前正在关闭,这意味着不需要在Close()事件处理程序中调用Deactivated方法:< / p>

    private bool _isClosing;

    protected override void OnClosing(CancelEventArgs e)
    {
        base.OnClosing(e);
        _isClosing = true;
    }

    protected override void OnDeactivated(EventArgs e)
    {
        base.OnDeactivated(e);
        if (!_isClosing)
            Close();
    }