3

I am new to MVVM and learning it with MVVM Light.

I have an application in wpf with a login window. When the user enters correct credentials the login window should close and a new MainWindow should open. The part of the login is already working but how can I open a new window and close the current (login.xaml)?

Also some parameters must be given to this new MainWindow.

Can anyone put me in the correct direction or provide me some info?

Kaizer
  • 651
  • 3
  • 9
  • 22
  • possible duplicate of [How to open a new window using MVVM Light Toolkit](http://stackoverflow.com/questions/3386349/how-to-open-a-new-window-using-mvvm-light-toolkit) – Patrick Quirk Jan 05 '15 at 15:29
  • Here's the code I typically use to close a login window and display the main application window : [How to Close a DialogWIndow after login and diplay main window?](http://stackoverflow.com/a/12861797/302677) – Rachel Jan 05 '15 at 15:29

1 Answers1

7

since you are using MvvmLight you could use the Messenger Class (a helper class within mvvmlight) which is used to send messages (notification + objects) between ViewModels and between ViewModels and Views, in your case when the login succeeded in the LoginViewModel (probably in the handler of the Submit Button) you need to send a message to the LoginWindow to close itself and show that other windows :

LogInWindow code behind

public partial class LogInWindow: Window
{       
    public LogInWindow()
    {
        InitializeComponent();
        Closing += (s, e) => ViewModelLocator.Cleanup();

        Messenger.Default.Register<NotificationMessage>(this, (message) =>
        {
            switch (message.Notification)
            {
                case "CloseWindow":
                    Messenger.Default.Send(new NotificationMessage("NewCourse"));
                    var otherWindow= new OtherWindowView();
                    otherWindow.Show();   
                    this.Close();            
                    break;
            } 
        }
    }
 }

and for in the SubmitButonCommandat the LogInViewModel (for example) send that closing Message:

private RelayCommand _submitButonCommand;
public RelayCommand SubmitButonCommand
{
    get
    {
        return _closeWindowCommand
            ?? (_closeWindowCommand = new RelayCommand(
            () => Messenger.Default.Send(new NotificationMessage("CloseWindow"))));
    }
}

and use the Same approach to send Object between LoginViewModel and that OtherWindowViewModel with the exception that this time you need to send Objects instead of just NotificationMessage : in the LoginViwModel:

 Messenger.Default.Send<YourObjectType>(new YourObjectType(), "Message");

and to receive that object in the OtherWindowViewModel :

Messenger.Default.Register<YourObjectType>(this, "Message", (yourObjectType) =>
                                                           //use it 
                                                             );
SamTh3D3v
  • 9,854
  • 3
  • 31
  • 47