This page shows the source for this entry, with WebCore formatting language tags and attributes highlighted.
Title
Real quick on MVVM
Description
A little while back, someone wrote <a href="https://old.reddit.com/r/csharp/comments/1gqjtel/i_cant_wrap_my_head_around_mvvm/" source="Reddit">I can't wrap my head around MVVM</a>, asking for help. I answered with a short example, reproduced below.
<abstract><abbr title="too long; didn't read">tl;dr</abbr>: Use the <a href="https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/">MVVM Toolkit</a> and try JetBrains ReSharper or Rider for more IDE assistance for binding and fixing up views.<fn></abstract>
The concept is that:
<ul>
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".
</ul>
<img src="{att_link}mvvm.png" href="{att_link}mvvm.png" align="none" scale="75%">
Why do we need this? Why not just bind the view directly to the model?
Consider a simple person:
<code>
record Person(
string FirstName,
string LastName,
Company Company,
DateTime BirthDate);
</code>
The view model might want to expose:
<code>
int Age => DateTime.Now.Year - _model.BirthDate.Year;
string FullName => $"{_model.FirstName} {_model.LastName}";
Company Company { get; }
IReadOnlyList<company> AvailableCompanies { get; }
</code>
The <c>AvailableCompanies</c> 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 <a href="https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/">MVVM Toolkit</a>. 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.
<hr>
<ft>I just saw in a .NET 9 release video that <a href="https://learn.microsoft.com/en-us/windows/apps/develop/data-binding/function-bindings"><c>x:bind</c></a> is a better alternative to the classic <c>binding</c>, which has better compiler and code-completion support (because it generates sources rather than using reflection). I haven't had a chance to investigate yet, though.</ft>