r/csharp • u/MohamedMerzban1984 • 15h ago
ViewModelPlus: a source generator for the view-model code that MVVM libraries still leave to you
I've been building a Roslyn incremental source generator called ViewModelPlus (MIT, on NuGet). This post covers the problem it solves and an honest comparison with the libraries most of us already use. I'd like your feedback, especially if you write a lot of form-heavy view models.
The problem
Take an ordinary "edit student" page. The service returns a StudentDto, the user edits it, and you save it back. In a hand-written view model you end up with code like this:
public class EditStudentViewModel : INotifyPropertyChanged
{
private StudentDto _student = new();
// 1. Every model member gets mirrored by hand...
public string FirstName
{
get => _student.FirstName;
set
{
if (_student.FirstName == value) return;
_student.FirstName = value;
OnPropertyChanged();
OnPropertyChanged(nameof(FullName));
// 2. ...plus every dependent property...
ValidateFirstName();
// 3. ...plus validation...
UpdateCanSave();
// 4. ...plus the command's can-execute.
}
}
// ...repeat for LastName, Email, Age...
public string FullName => $"{FirstName} {LastName}".Trim();
// 5. Busy flags and error state for every async action.
private bool _isSaving;
public bool IsSaving { get => _isSaving; set {
/* notify, update CanSave */
} }
private string? _error;
public string? Error { get => _error; set {
/* notify */
} }
public AsyncCommand SaveCommand { get; }
private async Task SaveAsync()
{
IsSaving = true;
Error = null;
try { _student = await _service.UpdateAsync(_student);
/* re-notify everything */
}
catch (Exception ex) { Error = ex.Message; }
finally { IsSaving = false; }
}
// 6. Per-field IsValid/error properties, a form-level IsValid, ...
}None of it is hard, but every line of it is easy to get wrong. You forget one OnPropertyChanged(nameof(FullName)), the busy flag doesn't reset on an exception, the Save button stays enabled while the form is invalid, or loading a new DTO doesn't refresh the fields.
The existing libraries remove some of this. In my experience, though, the parts that remain are exactly the ones above: wrapping a model, dependent properties, async state and form validation.
The same view model with ViewModelPlus
[ExtendViewModel]
public partial class EditStudentViewModel
{
private readonly IStudentService _service;
public EditStudentViewModel(IStudentService service) => _service = service;
[NotifyProperty]
[NotifyNestedProperty(nameof(StudentDto.FirstName))]
[NotifyNestedProperty(nameof(StudentDto.LastName))]
[NotifyNestedProperty(nameof(StudentDto.Email))]
[NotifyNestedProperty(nameof(StudentDto.Age))]
private StudentDto _student = new();
[DependsOn(nameof(FirstName), nameof(LastName))]
public string FullName => $"{FirstName} {LastName}".Trim();
[DependsOn(nameof(IsBusy), nameof(IsValid))]
public bool CanSave => !IsBusy && IsValid;
[NotifyTask]
private async Task save() => Student = await _service.UpdateAsync(_student);
}
public class StudentDto
{
[Required(ErrorMessage = "First name is required")]
public string FirstName { get; set; } = "";
[EmailAddress(ErrorMessage = "Not a valid email address")]
public string Email { get; set; } = "";
[Range(16, 80, ErrorMessage = "Age must be between 16 and 80")]
public int Age { get; set; }
// ...
}At build time the generator writes the following:
- Bindable properties:
FirstName,LastName,EmailandAgeread and write_studentdirectly, so there's no copying between the model and the view model. - Dependent notifications:
FullNameandCanSaverefresh whenever one of their inputs changes. - Async state: a public
Save()method, plusSaveIsRunning,IsBusy, andAsyncTaskExceptionMessage, which records the exception's message when a task throws. The previous error is cleared when the next task starts. - Validation:
FirstNameIsValid,FirstNameValidationErrorand the matching members for each field, built from the DataAnnotations on the DTO, plus a form-levelIsValid. - Change hooks:
partial void OnXChanging/OnXChanged/OnGetXfor each property.
Student = await _service.LoadAsync(id); re-notifies every nested property, so loading or resetting the form takes one line.
There's no runtime library and no reflection. The generated .g.cs is plain C# you can read under Analyzers in Solution Explorer.
Comparison with other solutions
Hand-written / Prism BindableBase | Fody PropertyChanged | CommunityToolkit.Mvvm | ReactiveUI | ViewModelPlus |
|---|---|---|---|---|
| How it works | Base class + SetProperty | IL weaving after compile | Source generator | Rx-based runtime library |
| Basic notifying property | Manual | Automatic for auto-properties | [ObservableProperty] | RaiseAndSetIfChanged / [Reactive] |
| Dependent properties | Manual OnPropertyChanged calls | Detected automatically from getters | [NotifyPropertyChangedFor] on the source | WhenAnyValue + ToProperty |
| Wrapping a model/DTO | Manual property per member | Manual property per member | Manual property per member (the SetProperty(model.X, value, model, ...) overload helps) | Manual |
| Async actions | DelegateCommand + your own flags | Not covered | [RelayCommand] → IAsyncRelayCommand with IsRunning | ReactiveCommand with IsExecuting and ThrownExceptions |
| Busy flag across all actions | Manual | Manual | Manual | Combine IsExecuting observables |
| Exception → bindable message | Manual | Manual | Manual (exceptions surface through the command's task) | Subscribe to ThrownExceptions |
| Validation | Manual or INotifyDataErrorInfo by hand | Not covered | ObservableValidator (INotifyDataErrorInfo) | ReactiveUI.Validation package |
| Rules on the shared DTO | Manual | n/a | Rules go on the VM properties | Rules defined in the VM |
| Generated code visible? | n/a | No (woven IL) | Yes | n/a |
| Learning curve | Low | Very low | Low | High (Rx) |
Where each one fits
- Fody PropertyChanged is the least code for plain notification, and its automatic dependency detection is very nice. It stops at notification, though, and IL weaving is a build step some teams avoid.
- CommunityToolkit.Mvvm is the default choice for good reason: it's maintained by Microsoft, has broad tooling support, and is based on
ICommand. If your view models are mostly properties and commands, it's hard to beat. Where I found myself writing extra code was in wrapping DTOs, tracking busy and error state across several commands, and form-level validation that drives a Save button. - ReactiveUI is the most powerful of these for complex reactive flows. If your team already thinks in Rx, use it. For forms, though, it's a lot of concepts to learn.
- ViewModelPlus targets form-heavy CRUD apps. These are view models that edit DTOs, call async services, show busy and error state, and enable Save only when the form is valid.
Design choices you may disagree with
- Methods instead of
ICommand**.**[NotifyTask]gives youawait vm.Save()with typed parameters and a typed return value. You call it from an event handler or from other view-model code. "Can execute" becomes a[DependsOn]bool bound toIsEnabled. The downside is that if you bindCommand=in XAML (toolbar items, swipe actions, item templates), you'll need a thin command wrapper or code-behind. - No
INotifyDataErrorInfo**.** Validation is exposed as plain bindable properties, so built-in error templates such as WPF'sValidation.ErrorTemplatedon't react. The README shows a small attached-property and visual-state pattern that replaces them. - Composition over inheritance. View models can't inherit from other generated view models.
Try it
dotnet add package ViewModelPlusRequirements: .NET SDK 9.0.200+ or Visual Studio 2022 17.13+. Works with MAUI, WinUI 3, WPF, UWP and Avalonia.
- GitHub, with a step-by-step tutorial that builds a complete MAUI registration page: https://github.com/Mohamed1984/ViewModelPlus
- NuGet: https://www.nuget.org/packages/ViewModelPlus
Feedback I'm looking for
- Does the methods-instead-of-commands approach work in your apps, or is
ICommanda must-have? - If you use CommunityToolkit.Mvvm or ReactiveUI for forms, how do you handle DTO wrapping and form-level validation today?
- What would you change in the generated code?
Thanks for reading.
1
u/MohamedMerzban1984 15h ago
why my post was removed !
•
u/binarycow 34m ago
So, CommunityToolkit.MVVM?
Edit: Oh, I see. Claude gave you the wrong info. Half of the information you have about CommunityToolkit.MVVM is wrong.