Click here to Skip to main content
15,347,523 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I have problem with Application.Current.Windows code. I don´t know, where is the problem. I found that the code should look like this:
var window2 = Application.Current.Windows
    .FirstOrDefault(window => window is Window2) as Window2;

and then
var richText = window2.RadioButton

What I have tried:

I tried to modify to my code:
var window1 = Application.Current.Windows
    .Cast<MainWindow>().FirstOrDefault(window => window is hra) as hra;
            var scitani = window1.scitani;

MainWindow is window where is the radiobutton with name scitani
hra is current window where I would like reference radiobutton

Error is: Cannot convert type 'type1' to 'type2' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion.

Can anyone tell me what to do with it?

Thank you
Updated 20-Apr-21 23:52pm

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[^]
dejf111 21-Apr-21 5:57am
Thank you!!!
Cast tries to cast each element of the WindowsCollection to the new type, and if it isn't possible it throws the exception you have seen.
Cast<Window> works fine because every element in the collection is derived from Window - but unless every window in your application derives from MainWindow then your second version will fail.
dejf111 21-Apr-21 5:57am
Thank you for advice!!!
OriginalGriff 21-Apr-21 7:08am
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900