Responsibility of a ViewModel

2020-03-17 22:12发布

问题:

I am building a tool which goal is to download a file based on a few parameters.

First step is to set (or retrieve) those parameters.

The different parameters sets are retrieved (let's say via configuration files) by a FileDownloadsManager : it knows exactly which parameters to use in order to download the right file.

those parameters are stored in a class, and I have a list of instances of this class.

That means that I can download my file with multiple possible parameters sets.

Around those ParameterSets, I've built ParametersSetsViewModels so that I can display them in a list, and add some View-Only properties. Internally, the ParametersSetsViewModels have a reference to the underlying ParametersSets used as a source for the members of the View Model.

now, when I select my parameters set, I would like the related file to be downloaded.

Whose responsibility should this be ?

I have this feeling that if the ViewModel is too active, by having a method that returns the downloaded file, this would be against the MVVM pattern; what is your take on this ?

Bonus : the download should be feasible in the background with BackgroundWorkers or WebClient's asynchronous methods.

回答1:

It seems to me that everyone assumes MVVM has no controllers as they left out the C. MVVM is actually a variation of MVC "that just adds ViewModels".

Maybe it should have been called MVCVM instead?

ViewModels are only there to offload the "GUI" code from the view and to contain any data for binding. ViewModels should not do any processing. A good test is that your ViewModel is testable via automated unit tests and has no dependencies on data sources etc. They should have no idea where the data is actually coming from (or who is displaying it).

Although it can be overlooked/avoided, a Controller is responsible for deciding what data model to display and in which views. The ViewModel is a bridge between Models (the M in MVVM) and Views. This allows simpler "separated" XAML authoring.

In answer to your question the processing should be handled by a controller. If it needs to update the ViewModel to show busy indicators etc that is fine, but it is not the View or the Model or the ViewModel's responsibility.