In pseudocode, this is what I am trying to do from a main window, with many non-modal sub-windows that can be opened and closed independently of the main window. (Think "preferences" or "find")
On pressing "OPEN WINDOW"
STEP 1: If window does not exist, create it.
STEP 2: Window now exists, so bring it to the front & make it visible.
(Step 2 is NB in case OPEN WINDOW is pressed while window is already open - I don't want multiple instances of it, just bring it to the front.)
On pressing "CLOSE WINDOW"
STEP 3: Close the window
ALT STEP 3: Hide the window
This is the code I have tried. I got as far as being able to open the window, and bring it to the front if OPEN WINDOW is pressed again while the window is open. However, once I close the window, I CANNOT get it to open a second time. I get an error stating that Window.Show() cannot be used once the window is closed.
public static void OpenWindowOnce(Window windowToOpen)
{
foreach (Window n in Application.Current.Windows)
{
//Checks if the window is already open, and brings it to the front if it is
if (n.GetType() == windowToOpen.GetType())
{}
else
{ windowToOpen.Show(); }
}
windowToOpen.Activate();
}
Where am I going wrong in my code/logic? Thank you, I am pretty new to coding and have spent weeks trying to get this right.
You cannot use a
Windowthat has been closed because its resources are disposed at that time. The solution is to simply create a newWindoweach time that you want to display it.I can see that you are passing in a
Windowobject and then trying to find the particular type ofWindow... in this case, you can use reflection to instantiate yourWindows from theirType. In particular, please see theActivator.CreateInstanceMethod page on MSDN. You could use it something like this: