When using MVVM, should you create new viewmodels, or swap out the models

mvvm

Say I have a viewmodel like this:

public class EmployeeViewModel
{
    private EmployeeModel _model;

    public Color BackgroundColor { get; set; }
    public Name
    {
        get { return _model.Name; }
        set
        {
            _model.Name = value;
            NotifyPropertyChanged(Name);
        }
    }
}

So this viewmodel binds to a view that displays an employee. The thing to think about is, does this viewmodel represent an employee, or a "displayable" employee. The viewmodel contains some things that are view specific, for instance the background color. There can be many employees, but only one employee view.

With this in mind, when changing the displayed employee, does it make sense to create a new EmployeeViewModel and rebind to the view, or simply swap out the EmployeeModel. Is the distinction even important, or is it a matter of style?

I've always leaned toward creating new viewmodels, but I am working on a project where the viewmodels are created once and the models are swapped out. I'm not sure how I feel about this, though it seems to work fine.

Best Answer

I think the question revolves around whether you are creating a new view or not.

If you have say multiple tabs, each one has an employeeView and corresponding viewmodel. when you open a new tab you instantiate a new view and viewmodel

If you have a single page, with 'next/prev employee' buttons then you probably have a single view and should stick with a single view model and change its properties.

If you switch out a viewmodel from a view you potentially muck up the bindings between the two. eg NotifyPropertyChanged as @konrad mentions

I've seen apps which create a new view each time which kind of works where you have a navigation controller or similar. But the more modern approach seems to be to have a single viewmodel tree for the app where its properties change overtime.

The multiple view approach can suffer from memory problems if you lose track of your views as you navigate around. Also if you are binding to a mediator or some other global events object you can find you are firing events on all your views when really you just want the active one to be triggered.

Related Topic