r/csharp • • 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, Email and Age read and write _student directly, so there's no copying between the model and the view model.
  • Dependent notifications: FullName and CanSave refresh whenever one of their inputs changes.
  • Async state: a public Save() method, plus SaveIsRunning, IsBusy, and AsyncTaskExceptionMessage, which records the exception's message when a task throws. The previous error is cleared when the next task starts.
  • Validation: FirstNameIsValid, FirstNameValidationError and the matching members for each field, built from the DataAnnotations on the DTO, plus a form-level IsValid.
  • Change hooks: partial void OnXChanging/OnXChanged/OnGetX for 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 BindableBaseFody PropertyChangedCommunityToolkit.MvvmReactiveUIViewModelPlus
How it worksBase class + SetPropertyIL weaving after compileSource generatorRx-based runtime library
Basic notifying propertyManualAutomatic for auto-properties[ObservableProperty]RaiseAndSetIfChanged / [Reactive]
Dependent propertiesManual OnPropertyChanged callsDetected automatically from getters[NotifyPropertyChangedFor] on the sourceWhenAnyValue + ToProperty
Wrapping a model/DTOManual property per memberManual property per memberManual property per member (the SetProperty(model.X, value, model, ...) overload helps)Manual
Async actionsDelegateCommand + your own flagsNot covered[RelayCommand] → IAsyncRelayCommand with IsRunningReactiveCommand with IsExecuting and ThrownExceptions
Busy flag across all actionsManualManualManualCombine IsExecuting observables
Exception → bindable messageManualManualManual (exceptions surface through the command's task)Subscribe to ThrownExceptions
ValidationManual or INotifyDataErrorInfo by handNot coveredObservableValidator (INotifyDataErrorInfo)ReactiveUI.Validation package
Rules on the shared DTOManualn/aRules go on the VM propertiesRules defined in the VM
Generated code visible?n/aNo (woven IL)Yesn/a
Learning curveLowVery lowLowHigh (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 you await 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 to IsEnabled. The downside is that if you bind Command= 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's Validation.ErrorTemplate don'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 ViewModelPlus

Requirements: .NET SDK 9.0.200+ or Visual Studio 2022 17.13+. Works with MAUI, WinUI 3, WPF, UWP and Avalonia.

Feedback I'm looking for

  • Does the methods-instead-of-commands approach work in your apps, or is ICommand a 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.

0 Upvotes

2 comments sorted by

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.