Reputation: 5087
I have a problem with my Application ending unexpectedly when a modal dialog, spawned from the main program window, closes normally. No unhandled exceptions are being thrown and none of the Closing
or Closed
events are fired on the Main application window.
Essentially I have a main/shell window, which is started in the Application code using ShellWindow.Show(). Through a menu the user can spawn a custom open dialog, this is a new window created and then shown using ShowDialog (the windows owner is set to that of the shell window).
When the dialog is closed (internally, by a command invoking _modalDialogWindow.Close()) the application closes, whereas I would only have expected the modal dialog to have closed.
Debugging the code indicates that the ShellWindow is dumped from memory, as the next executed line of code after _modalDialogWindow.Close() is it falling out of Application.Run() in the static program code.
If anyone has any ideas I am willing to try anything.
Upvotes: 5
Views: 1547
Reputation: 4012
Don't create any windows before you create your application, or they won't get registered properly. They won't show up in Application.Current.Windows or Application.Current.MainWindow. Then when you create your dialog window, your application will think that it is both the MainWindow and the only window.
Example of what not to do:
public partial class App : Application, ISingleInstanceApp
{
MyWindow win = new MyWindow(); //BAD! this is called inside new App(), but before the actual App constructor.
[STAThread]
public static void Main()
{
if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
{
var application = new App();
application.InitializeComponent();
application.Run();
// Allow single instance code to perform cleanup operations
SingleInstance<App>.Cleanup();
}
}
I had this problem too, your answer helped me figure out why.
Upvotes: 1
Reputation: 5087
It appears that, due to the MVVM/Ioc way I am designing the application window close events are being propagated further than they should. I don't understand this!
However, setting the Application.ShutDownMode to Explicit prevents the app from closing prematurely and I now have the desired behaviour.
Incidentally, turning on all the exceptions as suggested by declyclone didn't yield any exceptions that are thrown internally when then window is closed.
Upvotes: 5