Kaizer
Kaizer

Reputation: 661

MVVM Light WPF open new window

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?

Upvotes: 3

Views: 4865

Answers (1)

SamTh3D3v
SamTh3D3v

Reputation: 9944

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 
                                                             );

Upvotes: 7

Related Questions