7

I am creating a WPF application and following the MVVM pattern. But while doing things I Worry about that, Is it according to MVVM or not? Please guide with these doubts.

  1. Is is necessary to have a new ViewModel for each and every View? If not, then can creating a single MasterViewModel is violation of MVVM?

  2. How will ViewModels communicate with each other?

  3. MainWindow.xaml.cs where I'm integrating all the Views, should have only the initialization of viewmodel and assigning the DataContext will there or I can put other codes also?

  4. I am having my defined EventHandlers. Should I use them in ViewModel or outside of model-view-viewmodel?

gideon
  • 19,329
  • 11
  • 72
  • 113
PawanS
  • 7,033
  • 14
  • 43
  • 71

4 Answers4

3

You need some reading to do on MVVM. See the following questions:

Good examples of MVVM Template
Good Silverlight-MVVM Practice Example
MVVM Light Toolkit samples

For your questions:

  1. Some people follow this rule. : One-ViewModel-Per-View See Rule #2 on this article.

    It isn't absolutely necessary to follow this, but creating a MasterViewModel as using it everywhere, means you haven't understood MVVM yet.

    If you are referring to encapsulating common bits, yet, maybe, the MVVM Light Toolkit Has a ViewModelBase class for encapsulating a few things there.

  2. ViewModels won't communicate with each other, ViewModels will communicate with Views, and Views will communicate with other Views (and possibly instantiate ViewModels for them) some frameworks even have a loosely coupled way of doing this (ReactiveUI comes to mind)

  3. When a View is called, you could instantiate its corresponding ViewModel and then set it to the DataContext. But, there are many different patterns to doing this. @Euphporic mentions in the comments the ViewModel-first where ViewModels create Views through Ioc. See Which came first- The View or ViewModel.

    MVVM Light has a ViewModel locator which allows you to define a Views ViewModel statically inside XAML. It will automatically set when you create your view.

  4. Not completely clear here, (a) If you have events from Buttons, Menu, (anything deriving from ButtonBase) you should implement these using the Command Pattern. MVVM Light has a nice RelayCommand<T> that will help you here.

    (b) Other events, MVVM Light has EventToCommand behavior but Laurent (the author) warns about this turning into an Anti Pattern. I think sometimes you could just use plain events in your code behind and then call your ViewModels from there (But hey I'm not an expert here)


You've asked a couple of questions all over the place. The problem maybe you do not understand the WHY about MVVM.

In plain terms MVVM allows you keep the right thing at the right place, your application logic/control in the ViewModels, and then with the power of Silverlight/WPF databinding you hook your ViewModels to your views.

As Laurent explains, sometimes it doesn't have to be all that complicated. You don't even need a framework all the time.

I highly recommend watching his MIX video titled - "Understanding the Model-View-ViewModel Pattern" from here:
http://live.visitmix.com/Archive#VideoList

Community
  • 1
  • 1
gideon
  • 19,329
  • 11
  • 72
  • 113
  • "Views (and possibly instantiate ViewModels for them" Not in ViewModel-first scenario. – Euphoric Mar 29 '11 at 10:31
  • Thanks @giddy... I knew I didn't understood clearly the MVVM, but I started working on it due to some reason. Anyway I will get it and implement in a better way this time – PawanS Mar 29 '11 at 11:38
  • @giddy **2.ViewModels won't communicate with each other** How to solve the issues like, one view-model have any variable and that var value I want to change from other ViewModel – PawanS Mar 29 '11 at 11:50
  • @Gaps most frameworks have a way communicate, MVVMLight has a messenger class you can use to send variables. – gideon Mar 29 '11 at 12:30
  • Remember that view models raise `PropertyChanged`. You can use this fact to implement inter-view-model communication in most scenarios without introducing the kinds of dependencies that rule 2 is intended to avoid. – Robert Rossney Mar 29 '11 at 16:43
  • @robert But there would still be a dependency on the ViewModel called right? Like `ViewModelA` will have a reference to `ViewModelB` to call it at the right time? Or would this be interfaced. I did like ReactiveUI's way of having something like `IDialog` to load up a View loosely. – gideon Mar 29 '11 at 16:51
  • **NOTE**: Respectfully, I'm no expert so I would like to know if there was anything wrong that I mentioned in my question that spawned a downvote. Thanks – gideon Mar 29 '11 at 16:53
  • If A is logically coupled to B, that coupling has to be reflected in code somewhere. A's class is by far the most straightforward place to put that code. What you want to avoid is B being coupled to A - this logical dependency is none of B's business. There needs to be a good, articulable reason for introducing complexity that hides this logical dependency. "View models shouldn't contain references to other view models" is a rule of thumb, not a reason. – Robert Rossney Mar 29 '11 at 17:04
2

Is is necessary to have a new ViewModel for each and every View? If not, then can creating a single MasterViewModel is violation of MVVM?

No, you can have multiple views over a single view model, although it is typical to have a one view model to one view relationship. If you are thinking of one master view model for all views, then it could quickly become unmanageable.

How the all ViewModel will communicate with each other?

There are several ways, including direct references between view models, standard .NET events, or an event aggregator pattern.

MainWindow.xaml.cs, where I m integrating all the Views, should have only the initialization of viewmodel and assigning the DataContext will there or I can put other codes also?

Typically in MVVM, you would have no (or very little) code behind and use the XAML binding engine in a WPF app instead for viewmodel/view communication.

I am having my defined EventHandlers. Should I use them in ViewModel or outside of model-view-viewmodel?

Not quite sure what you mean by this, but you can use standard events for view model communication if required.

I would seriously consider using an MVVM framework for your app, my personal preference being Caliburn.Micro.

devdigital
  • 34,151
  • 9
  • 98
  • 120
2

[1] Is is necessary to have a new ViewModel for each and every View? If not, then can creating a single MasterViewModel is violation of MVVM?

Usually you need both a new ViewModel instance for each View instance and a different ViewModel class for each View class. Sometimes you want multiple Views for the same ViewModel, which is OK. If you are going with the ViewModel-first approach, then you may not always need a View class for each ViewModel class, but it also wouldn't hurt to have one.

[2] How will ViewModels communicate with each other?

If the ViewModels are directly related (e.g. a parent/child relationship) then one possibility is for one to have a direct reference to the other, or for one to subscribe to events on the other.

If the ViewModels are logically independent, then you should use some other mechanism such as Event Aggregator (in Prism) or Messenger (MVVM Light) or equivalent.

[3] MainWindow.xaml.cs where I'm integrating all the Views, should have only the initialization of viewmodel and assigning the DataContext will there or I can put other codes also?

You should not initialize ViewModels in your View code-behind. Models should be injected into the Views by a dependency injection (DI) container.

[4] I am having my defined EventHandlers. Should I use them in ViewModel or outside of model-view-viewmodel?

I could not understand what you are asking here.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • +1 great answer. For (3) Do you think thats always necessary, even if you have strongly typed VM's with no relations to each other? You would have and interface then for each VM? – gideon Mar 29 '11 at 11:05
  • @jon.... can you give any sample code or link. I didn't get any example for DI, as I know view code behind should not contain any behaviour related code... – PawanS Mar 30 '11 at 06:38
  • @GAPS: Look up `Inversion of Control` (first) and `Dependency Injection` (second) in Wikipedia -- there are nice short intros plus references and more links to follow. – Jon Mar 30 '11 at 15:59
1

1. Is it necessary to have a new ViewModel for each and every View? If not, then can creating a single MasterViewModel is violation of MVVM?

Not really. You can have certain ViewModels that correspond to a large number of views, each showing the same data in a different format. In fact, this is the whole rationale of MVVM in the first place -- segregation of display and business rules so that display format can be changed by loading different views.

You can also have one View that corresponds to a number of different ViewModels. This is code reuse on the display UI.

2. How will ViewModels communicate with each other?

Usually ViewModels communicate with Views via WPF Binding. That's why it is called MVVM and not MVC.

ViewModels can communicate with each other via a number of standard .NET means.

3. MainWindow.xaml.cs where I'm integrating all the Views, should have only the initialization of viewmodel and assigning the DataContext will there or I can put other codes also?

You usually separate each view into a separate XAML file. That makes it easy to substitue another view for a different format of the same data.

Usually, the recommendation is to separate your code into self-contained modules; i.e., one view one file, one viewmodel one file.

4. I am having my defined EventHandlers. Should I use them in ViewModel or outside of model-view-viewmodel?

Events should should be handled in views if they are purely UI-driven (i.e. has nothing to do with the data).

If an event should affect some change in the underlying data (or do some action on the business rules), you can in turn raise an event on the ViewModel. Notice that this event on the ViewModel can be different from the event on the View/UI.

Stephen Chung
  • 14,497
  • 1
  • 35
  • 48