System.InvalidOperationException was unhandled
Message="Cannot set Visibility or call Show or ShowDialog after window has closed."
I get this exception after running .Show() on a Window that has been closed. I have searched for a solution and the only one i can find is to hide the window instead of closing it. I can not make a new instance of my window so I guess I have to hide it instead. I'd like not to implement the hiding in the window but rather let another class handle all windows that closes. When I implement the window.hide() method like that it throws the same exception as above. My code is like this:
publicpartialclassApp : System.Windows.Application
{
privateWindow1 w1 = newWindow1();protectedoverridevoid OnStartup(StartupEventArgs e){
base.ShutdownMode = ShutdownMode.OnExplicitShutdown;EventManager.RegisterClassHandler(typeof(Window), Window.LoadedEvent, newRoutedEventHandler(WindowLoaded));NotifyIcon notifyIcon = newNotifyIcon();notifyIcon.Icon = TestNotifyIcon.Properties.
Resources.icon2;System.Windows.Forms.
MenuItem menuItem1 = new System.Windows.Forms.MenuItem("Window1", new System.EventHandler(menuItem1_Click));System.Windows.Forms.
MenuItem menuItem3 = new System.Windows.Forms.MenuItem("Exit", new System.EventHandler(menuItem3_Click));System.Windows.Forms.
MenuItem[] items = { menuItem1, menuItem3 };System.Windows.Forms.
ContextMenu cm = new System.Windows.Forms.ContextMenu(items);notifyIcon.ContextMenu = cm;
notifyIcon.Visible =
true;base.OnStartup(e);}
//Window is loadedvoid WindowLoaded(object sender, RoutedEventArgs e)
{
Window w = sender asWindow;if (w != null){
w.Closing +=
new System.ComponentModel.CancelEventHandler(w_Closing);}
}
//Window is closingvoid w_Closing(object sender, System.ComponentModel.CancelEventArgs e){
Window w = sender asWindow;if (w != null){
e.Cancel =
true;w.Hide(); //Crash
}
}
//Show windowvoid menuItem1_Click(object sender, EventArgs e){
w1.Show(); //Crash
}
//Exit applicationvoid menuItem3_Click(object sender, EventArgs e){
this.Shutdown();}
}
Project availible at: http://www.fkaudio.com/temp/TestNotifyIcon.zip
Thanks!
Lina