简体   繁体   English

如何获取WPF中打开的窗口数的计数

[英]how to get count of number of opened windows in WPF

I have a requirement that, if one window is opened then user can not allow to open other window , for that I have tried following code. 我有一个要求,如果打开了一个window ,则用户不允许打开其他window ,因为我尝试了以下代码。

if(System.Windows.Application.Current.Windows.Count == 0)
 {    
 //My code
 }

I am checking for currently opened window count, if it is greater then 1 then user can not open other window and that I will mention inside if statement, 我正在检查当前打开的window数,如果大于1,则用户无法打开其他窗口,我将在if语句中提及,

but when I run this code it gives me the error 但是当我运行这段代码时,它给了我错误

"Object reference not set to an instance of an object." “你调用的对象是空的。”

Any Solution 任何解决方案

You would be probably getting this error because, even for the first windows to be loaded, you would be applying this check. 您可能会收到此错误,因为即使对于第一个要加载的窗口,您也将应用此检查。 For this you can apply null check in your code. 为此,您可以在代码中应用null检查。 and for list of loaded windows, you can get it using Application, 对于已加载窗口的列表,您可以使用应用程序获取它,

var loadedWindows = Application.Current.Windows.Cast<Window>()
                                               .Where(win => win.IsLoaded);

If you want to know how many windows are opened from your application instance, you can do this 如果您想知道从应用程序实例中打开了多少个窗口,可以执行此操作

 l_WindowCount = 0;

 foreach(var Window in App.Current.Windows)
 {
    l_WindowCount += 1
 }

if(l_WindowCount > 1)
{
//do what you want to do here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM