36

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?

Bassie
  • 9,529
  • 8
  • 68
  • 159
sai sindhu
  • 1,155
  • 5
  • 20
  • 30
  • 1
    More details are badly needed here, about "some conditions", "new window", "another window", etc. – Alex Apr 23 '12 at 07:00
  • Sorry alex.. I just added a piece which makes more understandable – sai sindhu Apr 23 '12 at 07:09
  • @alex I think he means that he has two windows. When he starts the program, it should choose one of these windows based on some condition. sai sindhu: is that correct? – default Apr 23 '12 at 07:09

4 Answers4

66

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();
        }
    }
aifarfa
  • 3,939
  • 2
  • 23
  • 35
  • dont forget to include `using System.Windows;` – highboi Oct 07 '16 at 20:13
  • Interestingly, you should be extremely careful when instantiating windows. I had a login dialog that had to open before the MainWindow, so I did this, and after the LoginDialog closed, the app terminated. I fixed it by just instantiating the MainWindow first without actually showing it, and then *after* the Login dialog closed, run it. – TheXDS Feb 04 '18 at 05:16
  • i just wanna mention you need to add "window.Closed += (o, eventArgs) => Shutdown();" or your application wont terminate and will linger. Unless you configure ShutdownMode to last window. – CyberFox Oct 18 '18 at 03:45
  • What is the best way to access AuthService.Login(); assume I have Unity DI setup. I need to check if there is a active login in DB. _idenityService.GetLastLogin() how do I get the instance of _idenityService – HaBo Jul 11 '20 at 07:10
  • 1
    Note, you should just override `OnStartup` rather than subscribing to the `Startup` event. That way you're guaranteed to get the event before any other listeners. – Mark A. Donohoe Sep 01 '22 at 02:12
9

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.

Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
Gqqnbig
  • 5,845
  • 10
  • 45
  • 86
1

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.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • Remember to call the base constructor to still have the usual behavior, so: `public App() : base() { ... }`, otherwise App will not load your window. – AndreasHassing Feb 14 '17 at 07:28
0

I know this is quite old question. But I came in to similar issue, recently where I am using Dependency Injection with WPF .NET Core 3.1 felt someone would have similar challenge so posting this answer

Here is my startup where you can set your conditional startup window

protected override async void OnStartup(StartupEventArgs e)
        {
            await host.StartAsync();
            var userService = host.Services.GetService<IUserRepository>();
            var lastActiveUser = userService.LastActive();
            if (lastActiveUser != null)
            {
                DefaultWindow = host.Services.GetRequiredService<MainWindow>();
                DefaultWindow.Show();
            }
            else
            {
                DefaultWindow = host.Services.GetRequiredService<LoginWindow>();
                DefaultWindow.Show();
            }
            base.OnStartup(e);
        }

App Constructor for initializing host

public App()
        {
            host = Host.CreateDefaultBuilder()  // Use default settings
                                                //new HostBuilder()          // Initialize an empty HostBuilder
                   .ConfigureAppConfiguration((context, builder) =>
                   {
                       builder.SetBasePath(Directory.GetCurrentDirectory())
                       // Add other configuration files...
                       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
                       Configuration = builder.Build();

                   }).ConfigureServices((context, services) =>
                   {
                       ConfigureServices(context.Configuration, services);
                   })
                   .ConfigureLogging(logging =>
                   {
                       // Add other loggers...
                       logging.ClearProviders();
                       logging.AddConsole();
                   }).Build();
        }

Dependency Injection

private void ConfigureServices(IConfiguration configuration,
        IServiceCollection services)
        {
            _services = services;
            _services.Configure<AppSettings>(Configuration
                .GetSection(nameof(AppSettings)));

            _services.AddDbContext<SmartDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("SqlConnection"));
            });

            _services.AddScoped<IUserRepository, UserRepository>();
            _services.AddScoped<ILoginDataContext, LoginDataContext>();
            _services.AddTransient(typeof(MainWindow));
            _services.AddTransient(typeof(LoginWindow));
        }
HaBo
  • 13,999
  • 36
  • 114
  • 206