6

I have this click event in my main window to open a new window

private void Button_Click(object sender, RoutedEventArgs e)
{
    cm = new CanalesMain();

    cm.Show();

    cm.Canales.setValues();

}

My cm variable is defined as a member class in my main window because I need to load/refresh the setValues() method every 5 minutes (there's a TimeSpan and a EventHandler for that)

The thing is, in my "refresh data" method I have this if statement to ask if the cm variable is loaded and is not null (I mean, if the window was ever opened or if is opened, ask if isn't closed)

if (cm!=null && cm.IsLoaded)
{
    cm.Canales.setValues();
}

Is this the correct or best way to ask if my window is open?

4

4 回答 4

12

严格来说不,这不是正确的方法。IsLoaded并不意味着它Window是可见的,只是加载了(即使这在大多数情况下可能是等效的,但这意味着这个窗口已经创建了一次,它有一个句柄,没有提到它的可见性)。

您必须检查的是Visibility属性(它最终会改变Show() ),如果当前可见或尚未加载(或已加载但仍然存在),它将是Visible实际上隐藏)。WindowHidden

总结一下:

if (cm != null && cm.Visibility == Visibility.Visible)
{
}

请注意,如果Window是可见的,那么它是隐含的它已经被加载(它有一个句柄),但反之亦然(加载的窗口可能不可见,甚至可能在过去不可见)。

于 2013-10-29T14:06:32.333 回答
2

还有另一种方法可以检查哪些Windows 当前处于活动状态:

foreach (Window window in Application.Current.Windows)
{ 
    // Check for your Window here
}

如果您Window属于特定类型,那么您可以这样做:

foreach (Window window in Application.Current.Windows.OfType<YourWindow>())
{ 
    // Do something with your Window here
}

在显示之前,您Window不会出现在这里。

于 2013-10-29T14:18:53.133 回答
0

我认为扩展方法在这种情况下会非常有用,试试这个:

public static class WindowsExtensions
{
   public static bool IsOpened(this Window window)
   {
        return Application.Current.Windows.Cast<Window>().Any(x => x.GetHashCode() == window.GetHashCode());
   }
}

这使您能够像这样在每个窗口上进行调用:

var wind = new ChildWindow();
wind.ShowDialog();
var isOpened = wind.IsOpened();

您也可以查看以下内容:我如何知道是否打开了 WPF 窗口

有关Application.Windows的更多信息

于 2013-10-29T14:23:15.313 回答
0

如果您调用 myWindow.Show() 和 myWindow.Close(),myWindow.IsLoaded 应该会为您提供一个值,您可以使用该值来指示窗口是否打开。

于 2017-10-20T19:27:54.353 回答