WPF - choose startup window based on some condition

sai sindhu picture sai sindhu · Apr 23, 2012 · Viewed 31.4k times · Source

When running my program by clicking Run or pressing Ctrl + F5, is it possible to open different windows based on some check condition?

I.e if some condition is satisfied I wish to open a particular window, but if its not I want to open another window.

It should be like before opening any window it should first check for the condition like

if(File.Exists(<path-to-file>)
    Open Window 1
else
    Open Window 2

Is this possible?

Answer

aifarfa picture aifarfa · Apr 23, 2012

look into App.xaml

remove StartupUri="MainWindow.xaml"

add Startup="Application_Startup" new event Handler

<Application x:Class="YourProject.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Startup="Application_Startup">

form code behind App.xaml.cs create Application_Startup like...

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        //add some bootstrap or startup logic 
        var identity = AuthService.Login();
        if (identity == null)
        {
            LoginWindow login = new LoginWindow();
            login.Show();
        }
        else
        {
            MainWindow mainView = new MainWindow();
            mainView.Show();
        }
    }