Jiew Meng
Jiew Meng

Reputation: 88337

OK To Open new Window in ViewModel?

If I want to open a new Window, without needing any immediate information, is it ok to open it this way? I know with Dialogs I should use a service, but if I don't need any information back, it is quite troublesome and messy to add a new function into the service just to open a window?

// in ShellViewModel
public ICommand AboutCommand
{
    get
    {
        if (_aboutCommand == null) {
            _aboutCommand = new RelayCommand(delegate
            {
                var aboutView = new QuickImageUpload.Views.AboutView();
                aboutView.Show();
            });
        }
        return _aboutCommand;
    }
}

Upvotes: 2

Views: 731

Answers (2)

Robert Rossney
Robert Rossney

Reputation: 96870

To expand on what Tri Q said, once you do this, you've coupled the view model to WPF, and you won't be able to test it outside of the framework.

And even if this didn't actually keep NUnit (say) from functioning, it would still be a problem: How do you write a test to demonstrate that your view model is actually opening the window at the right time?

This is why you either want to implement a service, or even just have the view model raise an event. That gives you a way of writing a unit test that can verify that the window-opening logic is being triggered under the right circumstances.

Upvotes: 2

Tri Q Tran
Tri Q Tran

Reputation: 5690

You "could" do this, but you will be defeating the purpose of the MVVM pattern. The view models' purpose is to support unit testing (non STA thread execution) so when you start showing UI windows, your unit test will not work.

So to correct your understanding of using the service mediator for dialog boxes is not that it requires a return response of some kind, but to still allow view models to be executed in non STA threads, hence happy unit testers.

Hope that clears it up for you.

Upvotes: 2

Related Questions