Jensen
Jensen

Reputation: 1329

Where to handle logic in MVVM view models?

After some initial reading on WPF and MVVM i'm currently working on a small debug application for a digital IO controller. In this application i'v got a tree of view models, which looks like this:

IOControllerViewModel > ConfigurationViewModels > PortViewModels > ChannelViewModels

This corresponds to the business objects, where the IOController contains a set of Configurations, which then contains a list Ports, which then contains a list of Channels, which finally represent the input/output channels of the IO controller.

But now my question is where to handle the "logic"?

For example i want to toggle the state of a output channel. The IOControllerViewModel is currently the only instance, which has a reference to the business object, that contains the needed ToggleChannel() method. Now i see three options:

  1. Put the login inside the ChannelViewModel. Thus pass the necessary business object from my root all way down to the leafs.

  2. Put the logic inside the IOControllerViewModel. Thus an event or something similar must be fired by the ChannelViewModel and then handled by the IOControllerViewModel.

  3. Introduce a controller, which is responsible for any logic and publish the controller to all view models.

  4. Any other option? Best practice?

Thanks a lot!

Upvotes: 1

Views: 1717

Answers (2)

Rachel
Rachel

Reputation: 132568

Usually I put logic on the layer that uses it, and use a messaging system such as PRISM's EventAggregator or MVVM Light's Messenger to communicate between ViewModels. (If you're interested, I wrote a brief post about this here)

In your case, it depends on what layer handles the login. For example, if a LoginViewModel successfully authenticates a user, it would broadcast something like a UserAuthenticated message, containing relevant parameters. Interested ViewModels could then subscribe to UserAuthenticated messages, and handle them accordingly.

Keep in mind that with MVVM, your ViewModels are you application. The app should run just fine without any Views at all (such as from a Test script)

Upvotes: 3

MatthiasG
MatthiasG

Reputation: 4532

If I understood you correctly you're using a hierarchical structure which could live with just one ViewModel, the IOControllerViewModel. All those Configurations, Ports and Channels could be observable properties or collections of its corresponding item.

You would then just use an IOControllerView which contains an ItemsControl which accesses all configurations. In the DataTemplate of each configuration item you would have an ItemsControl which uses the ports as ItemsSource and so on.

It's not good to have more ViewModels than needed, especially if there's no need for a View because you could use a DataTemplate instead.

I hope I got you right.

Upvotes: 2

Related Questions