wpfvb.netwindowdirectcast

DirectCast any window, not only main window?


I've been trying to edit variables in other windows like in VB.NET using DirectCast. This seems to be working very well with the main window, as I use

Private Main As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)

But, I am unable to find a way to use this with a window other than the main one. For now, I am stuck using this

Dim WindowOne As New Window1
WindowOne.Show()

This works, but I would rather not have to create a new instance of the window each time I want it to open. I have tried using

Private WindowOne As Window1 = DirectCast(Application.Current.Windows.OfType(Of Window1).First(), Window1)

but it always gives me an error saying that "The sequence contains no elements".

Is there any other way to do this? What am I doing wrong?


Solution

  • The correct syntax is below.

    Private WindowOne As Window1 = Application.Current.Windows.OfType(Of Window1)().FirstOrDefault()
    If Not WindowOne Is Nothing Then
      'object is available here
    End If