Real quick on MVVM
Published by marco on
A little while back, someone wrote I can’t wrap my head around MVVM (Reddit), asking for help. I answered with a short example, reproduced below.
tl;dr: Use the MVVM Toolkit and try JetBrains ReSharper or Rider for more IDE assistance for binding and fixing up views.[1]
The concept is that:
- the (M)odel describes your data in the shape you want to store it, process it, etc.
- a (V)iew describes the elements of the UI.
- a (V)iew(M)odel mediates between these two “shapes”.
Why do we need this? Why not just bind the view directly to the model?
Consider a simple person:
record Person(
string FirstName,
string LastName,
Company Company,
DateTime BirthDate);
The view model might want to expose:
int Age => DateTime.Now.Year − _model.BirthDate.Year;
string FullName => $"{_model.FirstName} {_model.LastName}";
Company Company { get; }
IReadOnlyList<Company> AvailableCompanies { get; }
The AvailableCompanies
is for the drop-down menu.
So that’s why there are two models. We don’t want to pollute the data model with view-specific properties. Each view gets its own view model and you can have multiple views/viewModels on the same model. Nice.
The *mechanics* of binding the view to an object has nothing to do with MVVM. It’s *binding*, which is done by magic. This magic is made a lot easier if you use the MVVM Toolkit. The latest versions use source generators so you can actually *see* the magic binding code (in separate source-generated files).
I would also try JetBrains ReSharper or Rider because either of those tools provides a lot more code-completion, hints, warnings, and fixup assistance than a bare Visual Studio does.