How to change StartupUri of WPF Application?

Akash Kava picture Akash Kava · Dec 22, 2009 · Viewed 55.1k times · Source

I am trying to modify App.cs and load the WPF XAML files from code behind but its not working as it should.

No matter whatever I try to set as StartupUri it doesnt start, the program quits after this.

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        LoginDialog dlg = new LoginDialog();
        if (dlg.ShowDialog() != true)
            return;

        switch (dlg.ChoiceApp) { 
            case ChoiceApp.CustomerEntry:
                StartupUri = new Uri("/MyApp;component/Forms/CustomerEntry.xaml", 
                    UriKind.Relative);
                break;
            case ChoiceApp.VendorEntry:
                StartupUri = new Uri("/MyApp;component/Forms/VendorEntry.xaml", 
                    UriKind.Relative);
                break;
        }
    }
}

Now I even did trace and found out that LoginDialog is working correctly and is returning values correctly but setting "StartupUri" does not work.

I checked in reverse assembly that DoStartup method of App gets called after OnStartup, so technically my StartupUri must load, but it doesnt, in App.xaml startup uri is not at all defined.

Note: Bug Confirmed

I noticed that ShowDialog sets Application.MainWindow and when dialog ends, it sets it back to null, and because of this setting StartupUri does not work after calling Modal Dialog in OnStartup or Startup event.

There is no error or exception about invalid uri or anything like that.

This method works without DialogBox being called in Startup event or OnStartup, i think calling showdialog on this method causes something like its mainwindow being set to expired window and it shuts down after this.

Answer

tofutim picture tofutim · May 13, 2010

Akash, I ran into this exactly issue trying to implement a LoginDialog just like yours. The dialog does not have a bug, but rather the behavior is by design.

Not a bug. The default ShutdownMode of Application is OnLastWindowClosed, so as soon as the first window is closed your application will start shutting down! Change to OnExplicitShutdown and it will work, but you'll have to manage the shutdown.

See this previous StackOverflow question: WPF ShowDialog returns null immediately on second call