WPF——自动关闭无模式窗口

目录

介绍

无模问题的解决方案


介绍

无模式的窗口——它们非常方便。它们方便使用的东西太多了,无法迭代,所以你只能相信我的话。无模式窗口的问题在于,除非您在关闭主窗口之前(或之时)明确关闭它们,否则即使关闭主窗口它们也将保持打开状态。

无模问题的解决方案

该修补程序很简单,只需知道主窗口(或拥有窗口)何时关闭即可。为此,您只需处理所有者的Closing事件。我写了一种方法来处理这种琐事(您当然可以按照自己的意愿进行处理):

protected void HandleModeless()
{
    if (!this.IsModal())
    {
        // see if the owner was specified
        if (this.Owner == null)
        {
            // and if not, use the app's main window
            this.Owner = Application.Current.MainWindow;
        }
        // if we have an owner
        if (this.Owner != null)
        {
            // handle the close event so we can close the window when the 
            // owner closes
            Owner.Closing += this.Owner_Closing;
        }
    }
}

事件处理程序非常简单。它只是关闭窗体。

protected virtual void Owner_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    this.Close();
}

您可能已经注意到HandleModelss方法顶部的if条件。

if (!this.IsModal())

就我而言,这是一个Window扩展方法,它读取私有的Window属性,该属性可用于确定窗口是否为模态窗口。

public static class ExtendWpfWindow
{
    public static bool IsModal(this Window window)
    {
        // it should be safe to do this all in a single line of code because this is an 
        // extension method for the Window class
        return (bool)(typeof(Window).GetField("_showingAsDialog", 
               BindingFlags.Instance | BindingFlags.NonPublic).GetValue(window));
    }
}

您当然不必使用此扩展方法。实际上,您可以在窗口的代码中完成此操作:

protected void HandleModeless()
{
    if (!(bool)(typeof(Window).GetField("_showingAsDialog", 
               BindingFlags.Instance | BindingFlags.NonPublic).GetValue(window)))
    {
        ...
    }
}

甚至在窗口的代码中放置一个方法:

private bool IsModal()
{
    return ((bool)(typeof(Window).GetField("_showingAsDialog", 
               BindingFlags.Instance | BindingFlags.NonPublic).GetValue(window)));
}

protected void HandleModeless()
{
    if (!this.IsModal())
    {
        ...
    }
}

我个人认为使用扩展方法会更方便,特别是如果您的程序集具有常用的代码,并且您不想记住确切的方法来执行扩展方法为您做的事情时,更不用说扩展方法更易于重用。

我的拙见是,Microsoft应该在WPF框架中为我们处理此问题,因为除非在特殊情况下,开发人员不必担心这种事情。

https://www.codeproject.com/Tips/5295911/WPF-Auto-Closing-Modeless-Windows

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值