Sonntag, 30. Mai 2010

WPF Startup - a window too much...

So here is a simple problem: I want a login in my WPF application startup display just before the main window get created. Since the main window depends on the user entered I want to have that finished before all the binding automatism in my main window fire against services and the database.
So I removed the StartupUri from my App.xaml and did it myself in the OnAppStartup:

protected override void OnStartup(StartupEventArgs e)
{
var loginDialog = new LoginDialog();
bool? loginResult = loginDialog.ShowDialog();
if (!loginResult.HasValue || loginResult == false)
{
// exit application
return;
}
var mainWindow = new MainWindow();
mainWindow.Show();
}

Everything seems to be fine. Except that it's not working. The modal dialog pops up, but the main window never appears. In the debugger it clearly gets loaded, but the application is shut down immediately. Wait a moment, somewhere I read that the main window is treated specially...
Consulting the MSDN finally cleared things up: there is a property MainWindow which you can set to designate your main window. If you don't do that, the first window created will be the MainWindow - in my case the login dialog. But setting that property to your main window is not enough. I still had to handle a property called ShutDownMode. This is set to OnMainWindowClose by default. And apparently the shutdown was already initiated when the login window was closed. So I had to set this property to OnExplicitShutdown first (which could have been done in app.xaml also), then later on back to OnMainWindowClose.
So here is how it worked:

protected override void OnStartup(StartupEventArgs e)
{
ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
var loginDialog = new LoginDialog();
bool? loginResult = loginDialog.ShowDialog();
if (!loginResult.HasValue || loginResult == false)
{
// exit application
return;
}
var mainWindow = new MainWindow();
mainWindow.Show();
MainWindow = mainWindow;
ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
}

Keine Kommentare:

Kommentar veröffentlichen