c# - 系统.InvalidOperationException : Can not set Visibility

标签 c# .net wpf

我创建了一个窗口,只有当你点击它外面的时候它才能关闭。该代码在这里运行良好:

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

唯一的问题出现在窗口关闭时,例如,使用 alt + f4,特别是会出现以下异常:

You can not set Visibility to Visible or call Show, ShowDialog, Close WindowInteropHelper.EnsureHandle or while you are on the closure of the Window.

我怎样才能确保避免它?实际上,我已经使用 Try/Catch 处理了异常。

最佳答案

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

    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();
    }

关于c# - 系统.InvalidOperationException : Can not set Visibility,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32421731/

相关文章:

c# - Azure AD B2C 自定义策略,保护 API 连接器

wpf - 后台按钮不会关闭后台

c# - 在 List/IEnumerable 中重复数字

c# - 三元运算符既是左运算符又是右运算符..或者两者都不是

c# - 如何使用 OWIN 直接使用 token 通过 OpenID Connect 进行身份验证

c# - 代码中的表格布局被认为是错误的原因是什么?

c# - 如果类是对象的蓝图,那么静态类呢?

c# - CodeContracts 似乎没有任何原因导致构建失败

c# - 在 WPF 中,如何绑定(bind) LostFocus 但验证 PropertyChanged?

wpf - 当 slider 拇指移动绑定(bind)到计时器时,鼠标单击 WPF(时间) slider 无效