2
votes

I thought we should have no reference from View to ViewModel in MVVM Pattern. but just saw an MVVM Sample from code.msdn.microsoft in which ViewModel implements new Window and shows it;

By using MVVM-Light toolkit you use Messenger to Call or Open new Window and Still keep Separate the View and ViewModel form each other. Is it right to reference the View in ViewModel? Or it is wrong;

Do you suggest to call Views Directly from ViewModel for large(or medium) projects?

http://code.msdn.microsoft.com/windowsdesktop/Easy-MVVM-Examples-fb8c409f

2

2 Answers

2
votes

YAGNI.

Level of effort and complexity.

MVVM is just a pattern. A pattern you don't have to follow. Any little tool I write for my own use just uses a model, a viewmodel, and a view. The viewmodel exposes all properties I need for the view by INotifyPropertyChanged. The data is moved back and forth from viewmodel to model manually using ViewModel.FromModel(model) syntax. I don't bind to my models. I only use the model when saving/loading data; I don't hang onto it. My views are generated using dataTemplates and dataTemplateSelectors. If I have a property that should change the layout I expose that on the viewmodel and use a selector. Otherwise, I have a datatemplate for every viewmodel object. And it just works.

I call this a form of MVVM, even though it doesn't any toolkit or the exact MVVM pattern that Microsoft describes.

I would personally implement a service to drive commands from the viewmodel to generate new views and hookup the viewmodel. But that's because I have MVC experience, and I think generating views is easier to do using the MVC pattern, whereas desktop views work better using the MVVM pattern.

All my views are composed with contentControls. Setting the content is setting the viewmodel.

So I use a hybrid.

If your software isn't so complex to need the complete Microsoft endorsed MVVM pattern, why create the overhead code IMO. YAGNI.

1
votes

IMO, having a strong reference from the ViewModel to the View has 2 problems:

  • It breaks the testability of your ViewModel code. This means you won't be able to Unit Test your code so easily, and if you do you'll have to account for Dispatcher issues and the like.
  • It makes your ViewModels dependent on WPF assemblies and types. This means you won't be able to literally copy and paste your ViewModels into other applications or platforms such as Xamarin.Android or the like

If none of these are important to you, I don't see any reason why you wouldn't. Not doing so creates additional overhead in your code, by having to implement WindowManagers and whatnot.