Question

Hello everyone and thanks in advance for your time.

I'm currently learning MVVM using WPF for a small Biz App that I'm writing. I have read a lot of articles about the MVVM pattern and found that one of the key areas is to decouple the ViewModel from the View as much as possible.

I want to open a new Window in my app but I'm not sure if I should open it from the ViewModel using an ICommand or directly from the view using a standard event. Someone I work with suggested that that I should use commands, but then I thought that this would mean having a reference to a View in my ViewModel, which according to what I understand is precisely what the MVVM pattern focuses on avoiding.

My understanding is that if a window will open for navigation purposes only and the process of opening that new windows has no effect on the Model, then I should keep all of this on the view using standard events.

I know in sw development everything "depends", but guess my question is there a "right"/standard way of doing this?

Best regards, Daniel

Was it helpful?

Solution

Yes, VMs should communicate with Views utilizing the Events that Views can subscribe to...

In VM:

public event EventHandler<NotificationEventArgs<string>> DisplayOptionsNotice;  

In View:

private readonly MainViewModel mvm;
...
mvm = DataContext as MainViewModel;
mvm.DisplayOptionsNotice += DisplayOptionsWindow;
...
private void DisplayOptionsWindow(object sender, NotificationEventArgs<string> e)
{
    ...  
    optionsWindow = new OptionsWindow { Owner = this };
    optionsWindow.ShowDialog();
    ...
}

OTHER TIPS

but then I thought that this would mean having a reference to a View in my ViewModel, which according to what I understand is precisely what the MVVM pattern focuses on avoiding.

In general, the way this is handled is via some form of inversion of control. Most MVVM frameworks will provide a service of some form to open a window, and use a Service Locator or Dependency Injection to provide the service to the ViewModel.

This allows your ViewModel to stay decoupled from the specific view rendering framework - you'd pass the service the new VM and say "Show this VM in a window", and that code would be platform specific.

As Reed said Service locator or DI will do the work and wont breake the MVVM pattern. from my experience you will have to do three things: First check about the Service Locator or Di see what more friendly for you and implement it.
Second start making the interface of IWindow\IWindowDialog that your view (windows\ Messagebox - if you like) will implement for example.

the last thing is to implement the windows\ messages.

it will take time to do it from scratch (I did it) but if you will focus one thing at a time. you cut the time in half.

Good luck

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top