Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - choose startup window based on some condition

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?

like image 432
sai sindhu Avatar asked Apr 23 '12 06:04

sai sindhu


3 Answers

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();
        }
    }
like image 95
aifarfa Avatar answered Oct 18 '22 12:10

aifarfa


You can use App.xaml to start up your application and, as Nikhil Agrawal said, change StartupUri dynamically.

However, you can still start up your application from public static void Main(). Just delete the StartupUri="MainWindow.xaml" attribute in App.xaml, Add a Program class to your project containing a Main method, and then go to the project properties and set the startup object to YourAssemblyName.Program.

[STAThread]
public static void Main(string[] args)
{
    var app = new Application();
    var mainWindow = new MainWindow();
    app.Run(mainWindow);
}

Note, the STAThreadAttribute is required. If you need your own derived version of Application, such as how WPF projects create a derived App class by default, you can use that in the Main in place of Application. But, if you don't need it, you can just use the base Application class directly and remove the derived one from your project.

like image 29
Gqqnbig Avatar answered Oct 18 '22 11:10

Gqqnbig


In App.xaml we have an Application tag having StartupUri attribute. I think u should write this code in App.xaml.cs section

public App()
{
      // Your Code
}

and set StartUpUri to desired xaml file.

like image 1
Nikhil Agrawal Avatar answered Oct 18 '22 11:10

Nikhil Agrawal