Quote:
Application.Current.Windows.Cast<MainWindow>()
That will attempt to cast
all open windows to
MainWindow
. If any of your open windows are of a different type, you will get this error.
Use
OfType
instead, and remember to check for
null
:
MainWindow window1 = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
if (window1 != null)
{
var scitani = window1.scitani;
...
}
If you're absolutely certain that there will always be a
MainWindow
instance open, you could use
First
instead of
FirstOrDefault
, and skip the
null
check:
MainWindow window1 = Application.Current.Windows.OfType<MainWindow>().First();
var scitani = window1.scitani;
NB: This will throw an exception if there are no windows of the specified type open.
Enumerable.Cast<TResult>(IEnumerable) Method (System.Linq) | Microsoft Docs[
^]
Enumerable.OfType<TResult>(IEnumerable) Method (System.Linq) | Microsoft Docs[
^]
Enumerable.FirstOrDefault Method (System.Linq) | Microsoft Docs[
^]
Enumerable.First Method (System.Linq) | Microsoft Docs[
^]