Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF : How can i show my login window(project imported) before my application window?

I have made a project for a login WPF application that basically performs a database connection. Now I am developing an application (always in WPF) that need this login project to start. I have added the Login.Exe to the reference in my current project, but I can't find a way to force the start with the login and only after that run my MainWindow().

I'm currently trying something like this

namespace Administrator
{ 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Window login = new Login.MainWindow();
            login.Show();
        }
    }
}

My mainwindow.xaml has empty content, and this piece of code it shows the login form, but also a blank window. How can I achieve my goal?

like image 988
Daniele Sartori Avatar asked Dec 11 '22 11:12

Daniele Sartori


2 Answers

You can achieve this with the following pattern.

In your App.xaml change StartupUri="MainWindow.xaml" to Startup="ApplicationStart" and in your App.xaml.cs create the method ApplicationStart.

private void ApplicationStart(object sender, StartupEventArgs e)
{
    Window login = new Login.MainWindow();
    login.Show();

    // Determine if login was successful
    if (login.DataContext is LoginViewModel loginVM)
    {
        if (!loginVM.LoginSuccessful)
        {
            // handle any cleanup and close/shutdown app
        }
    }

    //show your MainWindow
}

I prefere this pattern because you can e.g. setup your DI container in the ApplicationStart or anything else you want to before your main view is shown.

like image 156
Mighty Badaboom Avatar answered May 12 '23 16:05

Mighty Badaboom


Set in the App.xaml the "ShutdownMode" and the "StartupUri":

   <Application x:Class="MyApp.App"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:MyApp"
                ShutdownMode="OnExplicitShutdown"
                StartupUri="Login.xaml">

The "StartupUri" is your login form.

like image 43
Adam Miklosi Avatar answered May 12 '23 15:05

Adam Miklosi