目录
介绍
无模问题的解决方案
介绍无模式的窗口——它们非常方便。它们方便使用的东西太多了,无法迭代,所以你只能相信我的话。无模式窗口的问题在于,除非您在关闭主窗口之前(或之时)明确关闭它们,否则即使关闭主窗口它们也将保持打开状态。
无模问题的解决方案该修补程序很简单,只需知道主窗口(或拥有窗口)何时关闭即可。为此,您只需处理所有者的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