2

I have a WPF application in MVVM architecture. When the application loads I need to show a 'Login' window where the user inputs username and password.

This is then passed to a ServiceLocator, which creates a client that connects to the WCF service.

Question :

How do I make the 'Login' window close once the client has successfully connected, without using any code-behind in the View's '.cs' file ?

John Miner
  • 893
  • 1
  • 15
  • 32
  • Hide the main window. Show it in case of successful login. Login window should be handled as any other dialog in MVVM. – Den Jul 12 '12 at 07:58

3 Answers3

1

I normally pass the ViewModel a Close Action in the IDialogService implementation.

public void ShowDialog(IDialogViewModel vm)
{
    // create the dialog view
    ...
    vm.CloseAction = () => dialog.Close();
    dialog.DataContext = vm;
    ...
    // show the dialog 
    dialog.ShowDialog();
}
Barracoder
  • 3,696
  • 2
  • 28
  • 31
0

I use a dialogservice for my login and expose an event

event EventHandler<RequestCloseEventArgs> RequestCloseDialog;

which closes the dialog when the client succesfully looged in.

edit: Here's an example

In your app.xaml.cs

protected override void OnStartup(StartupEventArgs e)
{
    var result = this._dialogService.Show("Login",this._myloginviewmodel);

    // When use click cancel in the login dialog
    if(!result)
    { 
        // Close app or whatever
    }

    // Access the properties of myloginviewmodel if you want

    // Now the only part of my app where I use view-first instead of viewmodel-first
    this.MainWindow = new MainWindow(_mainwindowviwemodel);
    this.MainWindow.Show();
}

That's all in my OnStartup(), and yes thats the codebehind from my app.xaml, but this is my application root and thats why this is ok for me. I don't have a AppViewModel or something like that because app.xaml will never "shown" to the user.

Community
  • 1
  • 1
blindmeis
  • 22,175
  • 7
  • 55
  • 74
  • how do you use it in the 'OnStartup' ? can you please post a code sample ? – John Miner Jul 12 '12 at 11:57
  • and like @pchajer said : doesn't this violate the MVVM as the logic are written in code behind which is against the MVVM ? – John Miner Jul 12 '12 at 11:58
  • no, because i have no viewmodel with a reference to the view. and the app.xaml.cs its not a "view codebehind" for me - its my application root. – blindmeis Jul 13 '12 at 05:54
0

You can override OnStartup method of Application class, where you can open the Login screen as a dialog, once user enter valid data you can return boolean value, on closing of login screen, you can do your further logic based on the boolean value.

pchajer
  • 1,584
  • 2
  • 13
  • 25