0

When a user has entered a correct password, a login window should close and the main window should open. I would like to do this from the ViewModel, however, the ViewModel may not know anything about the view.

I've searched a lot and apparantly the best way is to use the mediator pattern. I understand how this pattern works, but how to effectivly use it in this case?

the mediator will need:
- A reference to the View
- A reference to the ViewModel

The ViewModel will need a reference to the mediator.

Where do I need to create the mediator? I can't do it in the ViewModel as I won't be able to set the reference to the view. Creating the mediator in the view is an option as I can get the ViewModel out of the DataContext property, but then I will still need to pass the mediator to the ViewModel, which will only make the code more difficult.

How do I properly use a mediator for opening/closing windows?

Bv202
  • 3,924
  • 13
  • 46
  • 80

1 Answers1

1

the mediator pattern is used for communication between viewmodels not between view and viewmodel.

if you wanna handle dialogs from your viewmodel you can use a dialogservice like this one.

nevertheless when i wanna create a application login dialog, i do it this way.

in app.xaml.cs OnStartup()

  • create loginview
  • create login viewmodel
  • set datacontext for loginview to loginviewmodel
  • show loginview
  • EDIT: loginviewmodel check password and so on, if its ok then state is set in the loginviewmodel e.g. IsValidUser=true;
  • check result
  • EDIT: if dialogresult == "OK" and IsValidUser=true
  • the open mainwindow

here some of my code

    protected override void OnStartup(StartupEventArgs e)
    {
        //...
        ShutdownMode = ShutdownMode.OnExplicitShutdown;
        var vm = new LoginVM();
        var loginwindow = new LoginWindow();
        loginwindow.DataContext = vm;

        if (!result.HasValue || !result.Value || !IsValidUser)
        {
             Shutdown();
             return;
        }   

        //...
        var mainWindow = new MainWindow(new MainWindowViewModel(vm.Settings));

        mainWindow.Loaded += (sender, args) => splashScreen.Close();
        this.MainWindow = mainWindow;
        ShutdownMode = ShutdownMode.OnMainWindowClose;
        this.MainWindow.Show();

 }

ps: this is the only part of my apps where i use view first. the rest is all viewmodel first, which is much easier for me when doing mvvm.

Community
  • 1
  • 1
blindmeis
  • 22,175
  • 7
  • 55
  • 74
  • Thanks, but how do you check the result? I mean, the user enters the correct password, where is the code for opening the mainwindow and how is it triggered? – Bv202 Jun 20 '12 at 12:48
  • the code for checking is in your loginviewmodel, the code for opening the mainwindow is in your app.xaml.cs OnStartup() method – blindmeis Jun 21 '12 at 12:25