I have read several articles and tutorials on the MVVM pattern but there is one thing I couldn’t find distinct information about. Let’s take the following example:
The model contains two fields and properties:
private string username;
public string Username {
get; set;
}
private string password;
public string Password {
get; set;
}
Now, what should the view model contain? Should it only contain an instance of the model or should it also “re-expose” the model’s properties?
private Model _model;
public Model Model {
get; set;
}
Or…
private Model _model;
public Model Model {
get; set;
}
public Username {
get { return _model.Username; }
set { _model.Username = value; }
}
I have seen both variants in several articles and now am unsure which way is correct.
There is no general right or wrong answer to this question. It depends on the context and on personal preference.
I personally tend to not expose the model to the view directly. I like to have a ViewModel that is specifically tailored for the view. I don’t want to implement anything into model just because the view needs it (and I might be tempted to do so when the the model is exposed to the view).
In my ViewModel, I like to have have as little dependencies on the model as possible. If I can get away with it, I like to have a ViewModel that does not have a direct dependency to the Model at all (and have some external entity/service fill do the mapping).