MVVM ViewModel and Commands

mvvmwpf

I need a bit of help to understand the relationship between a viewmodel and a command, and the responsibility of the viewmodel.

I'll try to give an example (using Caliburn Micro).

I have a viewmodel class, a command class and a view with a Save button.

public class EditViewModel : Screen
{
    public bool CanSave
    {
        get { return IsDirty; }
    }

    public void Save()
    {
        var command = new SaveCommand(this); // command gets reference to VM
        command.Execute();
    }
}

public class SaveCommand
{
    private readonly EditViewModel _viewModel;

    public SaveCommand(EditViewModel viewModel)
    {
        _viewModel = viewModel;
    }

    public void Execute()
    {
       var work = _viewModel.Work;
       ..
       _viewModel.IsDirty = false;
    }
}

When the user click Save. Save() method is called and spins up a command that saves the work.

Now my question is, should the command have a reference to the viewmodel?

No) The viewmodel will have to pass the work to the command, which will have to pass the save result back to the viewmodel, which will update itself.

Yes) The command needs a reference to the viewmodel and properties needs to be public set-able.

No seems like the cleanest way, but also requires extra work, when the work or result aren't a simple bool or similar.

I guess the root it all is. What is the relationship between a viewmodel and it's command and the responsibility of the viewmodel ?

Is there a strong 1:1 "friend" relationship between the view-model and it's command, where code has just been moved to another class. So there is nothing wrong with the command having direct access to the viewmodel.

Another understanding, the viewmodel is a very simple class, almost only with properties and contains little logic. So the logic should be in the command.

Or the viewmodel is pretty smart and should contain application-logic. Commands are really only needed when there are either too many in one viewmodel or they are a bit complicated otherwise the command code can stay in the viewmodel.

I'm just rambling I guess, please help me out to understand the viewmodel and what it's responsibility is?

Best Answer

The command should be on the ViewModel.

In MVVM, the ViewModel is the thing that should contain all of the logic that drives the view. The view is the simple class - just a collection of UI controls whose state is bound to properties on the ViewModel.

Josh Smith wrote a really good intro to MVVM that should clear things up for you.

Related Topic