Reputation: 95
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.
Upvotes: 0
Views: 795
Reputation: 69959
You cannot use a Window
that has been closed because its resources are disposed at that time. The solution is to simply create a new Window
each time that you want to display it.
I can see that you are passing in a Window
object and then trying to find the particular type of Window
... in this case, you can use reflection to instantiate your Window
s from their Type
. In particular, please see the Activator.CreateInstance
Method page on MSDN. You could use it something like this:
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 = Activator.CreateInstance(typeof(YourWindow)) as YourWindow;
windowToOpen.Show();
}
}
windowToOpen.Activate();
}
Upvotes: 0