ViewModelPlus 1.1.88
dotnet add package ViewModelPlus --version 1.1.88
NuGet\Install-Package ViewModelPlus -Version 1.1.88
<PackageReference Include="ViewModelPlus" Version="1.1.88" />
<PackageVersion Include="ViewModelPlus" Version="1.1.88" />
<PackageReference Include="ViewModelPlus" />
paket add ViewModelPlus --version 1.1.88
#r "nuget: ViewModelPlus, 1.1.88"
#:package ViewModelPlus@1.1.88
#addin nuget:?package=ViewModelPlus&version=1.1.88
#tool nuget:?package=ViewModelPlus&version=1.1.88
ViewModelPlus
ViewModelPlus is a Roslyn incremental source generator that writes view-model boilerplate for .NET UI apps. You annotate private fields and methods of a partial class; at compile time it generates bindable properties, change notifications, async-operation state and validation.
Current versions: generator 1.1.88, annotations 1.0.10.
Contents
- Overview
- Installation
- Tutorial: a registration page, step by step
- Showing validation in XAML
- Reference
- More techniques
- Recommended practices
- Diagnostics
- Limitations
- Troubleshooting
- Internals
Overview
What it is. A C# source generator. You mark a class with [ExtendViewModel] and its fields and methods with a few attributes; the generator writes the other half of the partial class at build time. There is no runtime library and no reflection: the output is plain C# you can open and read.
What it is used for. Writing view models with far less code:
- Properties that notify the view, without hand-written setters.
- Computed properties that refresh when their inputs change.
- View-model properties mapped straight onto a model object, so there is no copying between model and view model.
- Async operations with running, busy and error state, called directly from the view.
- Two-level validation (each field, then the whole form) built on standard
System.ComponentModel.DataAnnotationsattributes.
Compatibility.
| Area | Supported |
|---|---|
| UI frameworks | Any that binds through INotifyPropertyChanged: .NET MAUI, WinUI 3, WPF, UWP, Avalonia. Generated code references only System, System.ComponentModel and System.ComponentModel.DataAnnotations. |
| Target frameworks | Any .NET that provides those namespaces (.NET 6 or later recommended). |
| Compiler | Roslyn 4.13 or later: .NET SDK 9.0.200+ or Visual Studio 2022 17.13+. |
| Language | C# only. Generated files use #nullable enable. |
Installation
ViewModelPlus ships as two NuGet packages, both netstandard2.0:
| Package | Contents |
|---|---|
ViewModelPlus |
The source generator (an analyzer; adds no runtime dependency). |
ViewModelPlus.Annotations |
The attributes you put in your code. |
<ItemGroup>
<PackageReference Include="ViewModelPlus" Version="1.1.88" />
<PackageReference Include="ViewModelPlus.Annotations" Version="1.0.10" />
</ItemGroup>
ViewModelPlus brings in ViewModelPlus.Annotations as a dependency, so the first reference alone is enough. Listing both keeps the attribute version explicit.
Add using ViewModelPlus; where you use the attributes, and using System.ComponentModel.DataAnnotations; where you use validation or [Display] attributes.
Tutorial: a registration page, step by step
The tutorial builds one .NET MAUI page, "Register student", adding one feature per step. Each step shows only what changes. The complete example at the end puts it all together.
Step 1: Notified properties
A notified property is a private field marked [NotifyProperty]. The generator creates the public property that the view binds to.
using ViewModelPlus;
namespace StudentsApp.ViewModels;
[ExtendViewModel]
public partial class RegisterStudentViewModel
{
[NotifyProperty]
private string _firstName = ""; // -> public string FirstName
[NotifyProperty]
private string _lastName = ""; // -> public string LastName
[NotifyProperty]
private string _email = ""; // -> public string Email
[NotifyProperty]
private int _age; // -> public int Age
}
<Entry Text="{Binding FirstName}" />
<Entry Text="{Binding LastName}" />
<Entry Text="{Binding Email}" Keyboard="Email" />
<Entry Text="{Binding Age}" Keyboard="Numeric" />
The rules. The class is public partial, top-level and inside a namespace. Each field is private (or protected) and starts with _ or a lowercase letter; the property name drops the _ and capitalizes the first letter.
What you get. Each generated setter ignores a value equal to the current one, stores the new value and raises PropertyChanged. The class implements INotifyPropertyChanged for you. Always assign through the property (FirstName = "x"), never the field, or the view is not told.
Reacting to changes. Each property comes with optional partial hooks. Implement the ones you need:
partial void OnEmailChanged(string newValue)
{
// runs after Email changed and the view was notified
}
The other hooks are OnXChanging (before the value is stored) and OnGetX (on every read). See Reference.
Step 2: Computed properties: DependsOn and AlsoNotify
A computed property derives its value from other properties. [DependsOn] tells the generator to re-notify it whenever one of its inputs changes.
[DependsOn(nameof(FirstName), nameof(LastName))]
public string FullName => $"{FirstName} {LastName}".Trim();
<Label Text="{Binding FullName}" FontSize="Title" />
[AlsoNotify] declares the same link from the other end, on the source field. These two declarations are equivalent:
// on the target
[DependsOn(nameof(FirstName))]
public string Initials => ...;
// on the source
[NotifyProperty]
[AlsoNotify(nameof(Initials))]
private string _firstName = "";
Prefer [DependsOn]: the dependency is written next to the code that uses it. A dependency is one level deep: if C depends on B and B depends on A, list A on C too.
Step 3: Nested properties
A view model usually edits a model object, a DTO the service accepts and returns. Without help, you either bind through it ({Binding Student.FirstName}), which does not notify, or duplicate every field in the view model and copy values in and out.
[NotifyNestedProperty] maps a view-model property directly onto a member of the model:
namespace StudentsApp.Models;
public class StudentDto
{
public int Id { get; set; }
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public string Email { get; set; } = "";
public int Age { get; set; }
}
[ExtendViewModel]
public partial class RegisterStudentViewModel
{
[NotifyProperty]
[NotifyNestedProperty(nameof(StudentDto.FirstName))]
[NotifyNestedProperty(nameof(StudentDto.LastName))]
[NotifyNestedProperty(nameof(StudentDto.Email))]
[NotifyNestedProperty(nameof(StudentDto.Age))]
private StudentDto _student = new(); // -> Student, FirstName, LastName, Email, Age
[DependsOn(nameof(FirstName), nameof(LastName))]
public string FullName => $"{FirstName} {LastName}".Trim();
}
The XAML from step 1 does not change. FirstName now reads and writes _student.FirstName, with the same notifications and hooks as before.
Why this simplifies view models:
- No duplicated fields. The model holds the data; the view model only declares which members the view edits.
- No mapping code. The object you send to the service is
_studentitself, already up to date. - Loading and resetting is one line.
Student = await _service.GetStudentAsync(id);re-notifies every nested property, so the whole form refreshes. - Rules live on the model. Validation and
[Display]attributes onStudentDtomembers are picked up by the nested properties (step 6), so a model shared with the server carries the same rules on both sides.
Use the two-argument form for a renamed or deeper member: [NotifyNestedProperty("City", "Address.City")].
Step 4: Notified tasks
Pages perform async work: save, load, sign in. Mark a private async method with [NotifyTask]; the generator creates a public method with the same parameters, plus state the view can bind to.
private readonly IStudentService _service;
public RegisterStudentViewModel(IStudentService service) => _service = service;
[NotifyTask]
private async Task<StudentDto> save() // -> public Task<StudentDto> Save()
{
var created = await _service.AddStudentAsync(_student);
Student = created;
return created;
}
[DependsOn(nameof(IsBusy))]
public bool CanSave => !IsBusy;
| Generated | Meaning |
|---|---|
Save() |
Call this from the view. It sets SaveIsRunning, awaits your method and resets the flag. |
SaveIsRunning |
True while Save runs. |
IsBusy |
True while any notified task of the view model runs. |
<Button Text="Save" Clicked="OnSaveClicked" IsEnabled="{Binding CanSave}" />
<ActivityIndicator IsRunning="{Binding IsBusy}" IsVisible="{Binding IsBusy}" />
private async void OnSaveClicked(object? sender, EventArgs e)
{
try
{
await _vm.Save();
await Shell.Current.GoToAsync("..");
}
catch (Exception) { } // see step 5
}
How notified tasks replace commands. In classic MVVM, every action needs a command object, a can-execute predicate, code to raise can-execute-changed when its inputs change, a busy flag and error handling. A notified task covers all of it:
| Concern | Command-based view model | ViewModelPlus |
|---|---|---|
| The action | A command property wrapping a method | The method itself, with [NotifyTask] |
| "Can run now?" | Can-execute predicate, refreshed by hand | A [DependsOn] bool property bound to IsEnabled, refreshed automatically |
| Running / busy state | Hand-written flags | XIsRunning, IsBusy |
| Errors | try/catch in every command | Captured into bindable messages (step 5) |
| Parameters and results | Single untyped parameter | Any typed parameters and a typed return value |
| Calling it | Through the command | await vm.Save() from an event handler, or from other view-model code |
Tasks compose with plain await: a task can call other generated task methods, and IsBusy stays true until the last one finishes.
Step 5: Errors and exception mapping
When a notified task throws, the generated wrapper copies the exception message into bindable properties, resets the running flags, and rethrows. When a task starts, the previous error is cleared, so the view always shows the outcome of the latest operation.
| Generated | Meaning |
|---|---|
AsyncTaskExceptionMessage |
Error of the latest operation: set when any task fails, cleared when any task starts. Settable. |
AsyncTaskErrorExists |
True while AsyncTaskExceptionMessage is set. Setting it to false clears the message. |
SaveTaskExceptionMessage |
Error of the latest Save run: set when Save fails, cleared when Save starts again. Other tasks do not touch it. |
Use AsyncTaskExceptionMessage for a page-level error bar. Use a task's own message to show an error next to a specific button that should stay visible while other tasks run.
<Label Text="{Binding AsyncTaskExceptionMessage}" IsVisible="{Binding AsyncTaskErrorExists}"
Style="{StaticResource ErrorText}" />
Map exceptions to messages users can read. Raw exception messages are usually technical. Translate them inside the task, choosing one of two strategies:
// Strategy 1: translate and rethrow.
// The wrapper records the friendly message, and the caller still learns that the call failed
// (here, the page does not navigate away).
[NotifyTask]
private async Task<StudentDto> save()
{
try
{
var created = await _service.AddStudentAsync(_student);
Student = created;
return created;
}
catch (HttpRequestException)
{
throw new InvalidOperationException("Could not reach the server. Check your connection.");
}
}
// Strategy 2: handle and report.
// The task completes normally; the view model shows the message and decides what happens next.
[NotifyTask]
private async Task resendCode()
{
try
{
await _service.ResendCodeAsync(_student.Email);
}
catch (ApiException ex) when (ex.StatusCode == 429)
{
AsyncTaskExceptionMessage = "Too many attempts. Try again in a minute.";
}
}
| Strategy | Use when | Note |
|---|---|---|
| Translate and rethrow | The caller's next step depends on success (navigate, close a dialog). | Wrap the call in try/catch; the message is already shown. XTaskExceptionMessage is set. |
| Handle and report | The view model drives what happens next, for example by changing a state property. | The call needs no try/catch. XTaskExceptionMessage is not set. |
With either strategy, catch at every call site that can still throw, especially in async void event handlers, where an uncaught exception ends the app. A message set by hand inside a task (strategy 2) is cleared the same way as a captured one, when the next task starts.
Step 6: Property validation
The validation model
ViewModelPlus validates at two levels.
- Property validation checks each field on its own. A property can have attribute rules (
[Required],[Range], ...) and a property validator method for rules attributes cannot express. The result isXIsValidandXValidationError, which drive the per-field feedback in the view. - Form validation checks whether the whole view model is in a state that can be submitted: every property is valid and the optional model validator passes. The result is
IsValid, which typically drives the submit button. You choose the form's initial state: computed from the data (the default, suited to update forms that load existing data) or invalid until the user edits it (EmptyFormInitialValidationState = true, suited to create forms where the user must enter data). See step 7.
flowchart LR
subgraph L1["Level 1: property validation (each field)"]
A["Attribute rules<br/>[Required], [Range], ..."] -->|all pass| B["Property validator<br/>[PropertyValidator]"]
B --> C["XIsValid<br/>XValidationError"]
A -->|first failure| C
end
subgraph L2["Level 2: form validation"]
D{"Every XIsValid<br/>true?"} -->|yes| E["Model validator<br/>[ModelValidator]"]
E --> F["IsValid<br/>IsValidChanged"]
D -->|no| F
end
C --> D
Both levels re-run automatically whenever a generated setter runs.
Attribute validation
Put System.ComponentModel.DataAnnotations attributes on the model members (for nested properties) or on [NotifyProperty] fields:
public class StudentDto
{
public int Id { get; set; }
[Required(ErrorMessage = "First name is required")]
[StringLength(40, ErrorMessage = "First name is too long")]
public string FirstName { get; set; } = "";
[Required(ErrorMessage = "Last name is required")]
public string LastName { get; set; } = "";
[Required(ErrorMessage = "Email is required")]
[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; }
}
For every property with rules, the generator adds:
| Generated | Meaning |
|---|---|
FirstNameIsValid |
True when all of FirstName's rules pass. |
FirstNameValidationError |
The message of the first failing rule, or null. |
TriggerFirstNameValidation() |
Re-runs FirstName's rules on demand. |
Rules run in declaration order and stop at the first failure. Always set ErrorMessage; for localized messages use the resource form, which is supported:
[EmailAddress(ErrorMessageResourceType = typeof(AppStrings), ErrorMessageResourceName = nameof(AppStrings.InvalidEmail))]
Property validators
For rules attributes cannot express, write a method returning bool that takes the property's value, mark it [PropertyValidator], and set the error message yourself. It runs only when the property's attributes pass.
[NotifyProperty]
[Required(ErrorMessage = "Please confirm the email")]
private string _confirmEmail = "";
[PropertyValidator(nameof(ConfirmEmail))]
private bool validateConfirmEmail(string value)
{
if (value == _student.Email)
return true;
ConfirmEmailValidationError = "Emails do not match";
return false;
}
XValidationError is cleared before the validator runs. The parameter type must match the property type exactly, including ?.
Showing property errors
Each field gets two bindings: an IsValid attached property on the input control, which switches it to an "Invalid" look, and an error label shown only while the field is invalid. The label's visibility comes from a get-only negation property in the view model:
[DependsOn(nameof(EmailIsValid))]
public bool EmailIsInvalid => !EmailIsValid;
<Entry Text="{Binding Email}" Keyboard="Email"
utils:Validation.IsValid="{Binding EmailIsValid}" />
<Label Text="{Binding EmailValidationError}" IsVisible="{Binding EmailIsInvalid}"
Style="{StaticResource ErrorText}" />
The attached property and its styles are a few lines of code you add once per app; Showing validation in XAML gives them and compares the alternatives.
Step 7: Form validation
IsValid tells whether the whole form can be submitted. Add it to the save condition:
[DependsOn(nameof(IsBusy), nameof(IsValid))]
public bool CanSave => !IsBusy && IsValid;
Choose the initial state.
| Form type | Setting | Behavior |
|---|---|---|
| Update form: loads existing data | [ExtendViewModel] (default) |
The state is computed from the data: a record loaded with valid data starts valid, and any errors show at once. |
| Create form: the user must enter data | [ExtendViewModel(EmptyFormInitialValidationState = true)] |
The form starts invalid, so Save is disabled; no field shows an error until the user edits it. |
The registration page is a create form:
[ExtendViewModel(EmptyFormInitialValidationState = true)]
public partial class RegisterStudentViewModel { ... }
Model validator: rules about the form as a whole. A method marked [ModelValidator] returns bool, takes no parameters, and runs after all properties pass. Use it for conditions that belong to no single field:
[NotifyProperty]
private bool _acceptedTerms;
[ModelValidator]
private bool validateForm() => _acceptedTerms;
Rules that depend on other properties. Validation re-runs automatically for the property being set. When a rule reads another property, re-check it when that property changes, and then re-check the form:
partial void OnEmailChanged(string newValue)
{
if (_confirmEmail.Length == 0)
return; // not edited yet: keep it error-free
TriggerConfirmEmailValidation();
TriggerModelValidation();
}
Always finish with TriggerModelValidation(): TriggerXValidation() alone updates XIsValid but not IsValid. Assigning a property its current value (ConfirmEmail = _confirmEmail) does not re-validate, because the setter ignores unchanged values.
Reacting to validity in code. IsValidChanged is raised whenever IsValid changes, which lets a parent view model track child view models (see More techniques).
The complete example
View model
using System.ComponentModel.DataAnnotations;
using StudentsApp.Models;
using StudentsApp.Services;
using ViewModelPlus;
namespace StudentsApp.ViewModels;
[ExtendViewModel(EmptyFormInitialValidationState = true)]
public partial class RegisterStudentViewModel
{
private readonly IStudentService _service;
public RegisterStudentViewModel(IStudentService service) => _service = service;
// Notified and nested properties
[NotifyProperty]
[NotifyNestedProperty(nameof(StudentDto.FirstName))]
[NotifyNestedProperty(nameof(StudentDto.LastName))]
[NotifyNestedProperty(nameof(StudentDto.Email))]
[NotifyNestedProperty(nameof(StudentDto.Age))]
private StudentDto _student = new();
[NotifyProperty]
[Required(ErrorMessage = "Please confirm the email")]
private string _confirmEmail = "";
[NotifyProperty]
private bool _acceptedTerms;
// Computed properties
[DependsOn(nameof(FirstName), nameof(LastName))]
public string FullName => $"{FirstName} {LastName}".Trim();
[DependsOn(nameof(IsBusy), nameof(IsValid))]
public bool CanSave => !IsBusy && IsValid;
// Property validation
[PropertyValidator(nameof(ConfirmEmail))]
private bool validateConfirmEmail(string value)
{
if (value == _student.Email)
return true;
ConfirmEmailValidationError = "Emails do not match";
return false;
}
partial void OnEmailChanged(string newValue)
{
if (_confirmEmail.Length == 0)
return;
TriggerConfirmEmailValidation();
TriggerModelValidation();
}
// Negations for the view
[DependsOn(nameof(FirstNameIsValid))] public bool FirstNameIsInvalid => !FirstNameIsValid;
[DependsOn(nameof(LastNameIsValid))] public bool LastNameIsInvalid => !LastNameIsValid;
[DependsOn(nameof(EmailIsValid))] public bool EmailIsInvalid => !EmailIsValid;
[DependsOn(nameof(ConfirmEmailIsValid))] public bool ConfirmEmailIsInvalid => !ConfirmEmailIsValid;
[DependsOn(nameof(AgeIsValid))] public bool AgeIsInvalid => !AgeIsValid;
// Form validation
[ModelValidator]
private bool validateForm() => _acceptedTerms;
// Notified task with exception mapping
[NotifyTask]
private async Task<StudentDto> save()
{
try
{
var created = await _service.AddStudentAsync(_student);
Student = created;
return created;
}
catch (HttpRequestException)
{
throw new InvalidOperationException("Could not reach the server. Check your connection.");
}
}
}
Page
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:vm="clr-namespace:StudentsApp.ViewModels"
xmlns:utils="clr-namespace:StudentsApp.Utilities"
x:Class="StudentsApp.Pages.RegisterStudentPage"
x:DataType="vm:RegisterStudentViewModel"
Title="Register student">
<ScrollView>
<VerticalStackLayout Padding="20" Spacing="6">
<Label Text="{Binding FullName}" FontSize="Title" />
<Label Text="First name" />
<Entry Text="{Binding FirstName}" utils:Validation.IsValid="{Binding FirstNameIsValid}" />
<Label Text="{Binding FirstNameValidationError}" IsVisible="{Binding FirstNameIsInvalid}" Style="{StaticResource ErrorText}" />
<Label Text="Last name" />
<Entry Text="{Binding LastName}" utils:Validation.IsValid="{Binding LastNameIsValid}" />
<Label Text="{Binding LastNameValidationError}" IsVisible="{Binding LastNameIsInvalid}" Style="{StaticResource ErrorText}" />
<Label Text="Email" />
<Entry Text="{Binding Email}" Keyboard="Email" utils:Validation.IsValid="{Binding EmailIsValid}" />
<Label Text="{Binding EmailValidationError}" IsVisible="{Binding EmailIsInvalid}" Style="{StaticResource ErrorText}" />
<Label Text="Confirm email" />
<Entry Text="{Binding ConfirmEmail}" Keyboard="Email" utils:Validation.IsValid="{Binding ConfirmEmailIsValid}" />
<Label Text="{Binding ConfirmEmailValidationError}" IsVisible="{Binding ConfirmEmailIsInvalid}" Style="{StaticResource ErrorText}" />
<Label Text="Age" />
<Entry Text="{Binding Age}" Keyboard="Numeric" utils:Validation.IsValid="{Binding AgeIsValid}" />
<Label Text="{Binding AgeValidationError}" IsVisible="{Binding AgeIsInvalid}" Style="{StaticResource ErrorText}" />
<HorizontalStackLayout>
<CheckBox IsChecked="{Binding AcceptedTerms}" />
<Label Text="I accept the terms" VerticalOptions="Center" />
</HorizontalStackLayout>
<Label Text="{Binding AsyncTaskExceptionMessage}" IsVisible="{Binding AsyncTaskErrorExists}" Style="{StaticResource ErrorText}" />
<ActivityIndicator IsRunning="{Binding IsBusy}" IsVisible="{Binding IsBusy}" />
<Button Text="Save" Clicked="OnSaveClicked" IsEnabled="{Binding CanSave}" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
Code-behind and registration
public partial class RegisterStudentPage : ContentPage
{
private readonly RegisterStudentViewModel _vm;
public RegisterStudentPage(RegisterStudentViewModel vm)
{
InitializeComponent();
BindingContext = _vm = vm;
}
private async void OnSaveClicked(object? sender, EventArgs e)
{
try
{
await _vm.Save();
await Shell.Current.GoToAsync("..");
}
catch (Exception)
{
// already shown through AsyncTaskExceptionMessage
}
}
}
// MauiProgram.cs
builder.Services.AddSingleton<IStudentService, StudentService>();
builder.Services.AddTransient<RegisterStudentViewModel>();
builder.Services.AddTransient<RegisterStudentPage>();
The Validation attached property and the ErrorText and Entry styles are in the next section.
See the generated code. In Solution Explorer: Dependencies > Analyzers > ViewModelPlus > RegisterStudentViewModel.g.cs. Or set <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> to write it under obj/.
Showing validation in XAML
ViewModelPlus exposes validation as plain bindable properties (XIsValid, XValidationError, IsValid). It does not implement INotifyDataErrorInfo, so built-in framework error visuals do not react. Showing errors is therefore up to the view, and two pieces cover it well:
- An attached property on the input control that switches the control's look between valid and invalid.
- An error label under the control, with its text bound to
XValidationErrorand its visibility bound to the view model'sXIsInvalidproperty.
.NET MAUI: attached property and visual states
In MAUI this is an attached property (BindableProperty.CreateAttached), the same concept as an attached property in WPF and WinUI. It is not a MAUI Behavior<T>: it needs no behavior instance per control and no triggers. Add this class once:
namespace StudentsApp.Utilities;
public static class Validation
{
public static readonly BindableProperty IsValidProperty =
BindableProperty.CreateAttached(
"IsValid", typeof(bool), typeof(Validation),
defaultValue: true, // a control starts valid
propertyChanged: OnIsValidChanged);
public static bool GetIsValid(BindableObject view) => (bool)view.GetValue(IsValidProperty);
public static void SetIsValid(BindableObject view, bool value) => view.SetValue(IsValidProperty, value);
private static void OnIsValidChanged(BindableObject view, object oldValue, object newValue)
{
if (view is VisualElement element)
VisualStateManager.GoToState(element, (bool)newValue ? "Valid" : "Invalid");
}
}
Then define the look of the "Invalid" state in the control's style, in its own visual state group:
<Style TargetType="Entry">
<Setter Property="VisualStateManager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="Focused" />
<VisualState x:Name="Disabled">
<VisualState.Setters>
<Setter Property="Opacity" Value="0.5" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="ValidationStates">
<VisualState x:Name="Valid" />
<VisualState x:Name="Invalid">
<VisualState.Setters>
<Setter Property="TextColor" Value="#F04438" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
</Style>
<Style x:Key="ErrorText" TargetType="Label">
<Setter Property="TextColor" Value="#F04438" />
<Setter Property="FontSize" Value="12" />
</Style>
Three details matter:
- Use a separate
ValidationStatesgroup. MAUI itself moves controls betweenCommonStates(Normal, Focused, Disabled). An "Invalid" state placed inCommonStatesis replaced as soon as the control gains focus or is re-enabled; a separate group is left alone. - Default the attached property to
true. The change callback runs only when the value changes. With a default offalse, a field that is invalid when the page opens (an update form loaded with bad data) never gets the invalid look. - Composite controls need their own states. A
ContentViewthat wraps anEntryor aBorderhas no visual states of its own, soGoToStateon it does nothing. Declare theValidationStatesgroup on the control itself, and restyle inner elements withSetter TargetName="...".
WinUI and WPF
The same two pieces apply, with DependencyProperty.RegisterAttached instead of BindableProperty.CreateAttached. In the change callback, set a visual cue (for example BorderBrush from a resource) rather than replacing the control's Style, which would discard any style the page set on it.
Comparing approaches
| Approach | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Attached property + visual state + error label (recommended) | The attached property moves the control to an "Invalid" visual state; a label shows XValidationError while XIsInvalid is true. |
One line per control; the look is defined once in styles and is theme-aware; the message is always visible, including on touch screens; works for any control that defines the states. | Each control style (and each composite control) must define the ValidationStates group. |
| Attached property that swaps the control's style and shows a tooltip | The callback replaces Style with an error style and attaches a tooltip containing the message. |
Compact forms with no extra labels; suits dense desktop layouts. | Replacing Style drops the control's own style; tooltips appear only on hover, so touch users never see the message. |
| Triggers in XAML | Each control has a DataTrigger on XIsValid. |
No helper code. | Verbose and repeated for every control; the look is spread across pages. |
Value converter on IsVisible |
A boolean inverter converts XIsValid for the label. |
No view-model change. | An extra class and logic in XAML; a negation property in the view model does the same job and can be unit-tested. |
Recommendation: use the attached property with a ValidationStates visual state for the control's look, and an inline error label bound to XValidationError and XIsInvalid for the message. Name the negation properties consistently (XIsInvalid) across the app.
Reference
Attributes
All attributes live in the ViewModelPlus namespace.
| Attribute | Placed on | Purpose |
|---|---|---|
[ExtendViewModel] |
class | Turns the class into a generated view model; holds the options. |
[NotifyProperty] |
private/protected field | Generates a public notifying property. |
[DependsOn(...)] |
[NotifyProperty] field, or any property |
Re-notify this property when the listed ones change. |
[AlsoNotify(...)] |
[NotifyProperty] field |
When this property changes, also notify the listed ones. |
[NotifyNestedProperty(...)] |
[NotifyProperty] field of a class type |
Generates a property mapped to a member of the field's object. Repeatable. |
[NotifyTask] |
private async method | Generates a public wrapper with running, busy and error state. |
[PropertyValidator("X")] |
method bool m(T value) |
Custom rule for property X. |
[ModelValidator] |
method bool m() |
Form-level rule that must pass for IsValid. One per class. |
ExtendViewModel options
| Option | Default | Effect when true |
|---|---|---|
Validate |
true |
Generates validation members and runs validation in every setter. Set false for display-only view models. |
EmptyFormInitialValidationState |
false |
Create-form behavior: fields report valid until first edited, and IsValid starts false. |
GenerateUnifiedBusyFlag |
true |
Generates IsBusy. |
HandleAsyncTaskExceptions |
true |
Task wrappers record exception messages before rethrowing. Keep it on. |
GenerateUnifiedAsyncTaskExceptionProperty |
true |
Generates AsyncTaskExceptionMessage and AsyncTaskErrorExists. Needs HandleAsyncTaskExceptions. |
GeneratePropertyLabels |
true |
Generates XLabel from [Display(Name = ...)]. |
GeneratePropertyDescriptions |
true |
Generates XDescription from [Display(Description = ...)]. |
Generated members
For each notified or nested property X of type T:
| Member | Description |
|---|---|
T X { get; set; } |
The setter is private with [NotifyProperty(PrivateSetter = true)]. |
partial void OnXChanging(T newValue, T oldValue) / OnXChanging(T newValue) |
Before the value is stored. Cannot cancel. |
partial void OnXChanged(T newValue, T oldValue) / OnXChanged(T newValue) |
After notifications and validation. |
partial void OnGetX() |
At the start of every read. |
string XLabel, string XDescription |
From [Display]; empty when there is none. Public read-only fields. |
bool XIsValid, string? XValidationError, bool TriggerXValidation() |
When the property has validation rules. |
For each notified task X:
| Member | Description |
|---|---|
Task X(...) / Task<T> X(...) |
The public wrapper. |
bool XIsRunning |
True while X runs. |
string? XTaskExceptionMessage |
Message of X's last exception. |
Once per view model:
| Member | Description |
|---|---|
bool IsBusy |
True while any task runs. |
string? AsyncTaskExceptionMessage, bool AsyncTaskErrorExists |
Last exception message of any task; whether one is set. |
bool IsValid, bool TriggerModelValidation(), event Action<TViewModel>? IsValidChanged |
Form validation. |
event PropertyChangedEventHandler? PropertyChanged, void OnPropertyChanged(string) |
The INotifyPropertyChanged implementation. |
NotifyNestedProperty forms
| Form | Meaning |
|---|---|
(string propertyName) |
Property name and path are the same. |
(string propertyName, string path) |
path is a dot-separated chain of members: ("City", "Address.City"). |
DependsOn = new[] {...} |
Same as [DependsOn], for this nested property. |
AlsoNotify = new[] {...} |
Same as [AlsoNotify], for this nested property. |
With a nullable base field (private DepartmentDto? _department), nested properties become nullable and read null while the base is null; writes are ignored until it is set.
Names you can depend on
[DependsOn] accepts any notified or nested property, plus: IsValid, XIsValid, IsBusy, XIsRunning, AsyncTaskExceptionMessage, and XException for task X's own message.
More techniques
Validating child view models
A form can contain a list of rows, each edited through its own view model: for example, one mark per student. The form is valid only when every row is valid. Three generated pieces make this work:
- Each row is itself an
[ExtendViewModel]class. It validates its own fields and gets its ownIsValid. - Each row raises
IsValidChanged. The generator addspublic event Action<TViewModel>? IsValidChangedto every view model withValidateon (the default). You don't implement it. It fires only when the row'sIsValidactually changes value, after an edit through a generated setter or a call toTriggerModelValidation(). Its argument is the row whose validity changed. - The parent validates the collection with a property validator on the collection property.
The row:
[ExtendViewModel]
public partial class MarkEntryViewModel
{
[NotifyProperty]
[Range(0, 100, ErrorMessage = "Mark must be 0 to 100")]
private int _mark;
}
// generated: Mark, MarkIsValid, MarkValidationError, IsValid, IsValidChanged, ...
The parent:
[ExtendViewModel]
public partial class MarksViewModel
{
public MarksViewModel()
{
_entries.CollectionChanged += onEntriesCollectionChanged;
}
[NotifyProperty]
private ObservableCollection<MarkEntryViewModel> _entries = new();
// The collection is valid when every row is valid.
[PropertyValidator(nameof(Entries))]
private bool validateEntries(ObservableCollection<MarkEntryViewModel> entries)
=> entries.All(e => e.IsValid);
// Watch rows as they are added and removed.
private void onEntriesCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
foreach (MarkEntryViewModel row in e.OldItems)
row.IsValidChanged -= onRowValidityChanged;
if (e.NewItems != null)
foreach (MarkEntryViewModel row in e.NewItems)
row.IsValidChanged += onRowValidityChanged;
revalidateEntries(); // adding or removing a row can change the result too
}
private void onRowValidityChanged(MarkEntryViewModel row) => revalidateEntries();
// Validation runs automatically only in generated setters, and editing a row does not
// set Entries, so re-check the collection and then the form.
private void revalidateEntries()
{
TriggerEntriesValidation();
TriggerModelValidation();
}
}
Things to keep in mind:
- Subscribe to every row, including later ones. Listening to
CollectionChanged, as above, covers rows added after the page opens. A one-time loop over the current rows misses them. Clear()gives no list of removed rows. It raises aResetchange withOldItemsset tonull, so the handlers stay attached to the old rows. Remove rows one by one, or unsubscribe from all rows before callingClear().- Replacing the whole collection (
Entries = new(...)) needs the same care. Move theCollectionChangedand row subscriptions in theOnEntriesChanged(newValue, oldValue)hook. AssigningEntriesre-validates it automatically. - New blank rows start invalid if the row class uses
EmptyFormInitialValidationState = true. The form then stays invalid until those rows are filled in, which is usually what you want.
Lazy loading with OnGetX
OnGetX() runs on every read of X and of its nested properties, so it can fetch data the first time the view asks for it:
[NotifyProperty(PrivateSetter = true)]
[NotifyNestedProperty("DepartmentName", nameof(DepartmentDto.Name))]
private DepartmentDto? _department;
private Task? _departmentLoad;
partial void OnGetDepartment()
{
if (_department == null)
_departmentLoad ??= LoadDepartment(); // start the load once
}
[NotifyTask]
private async Task loadDepartment()
=> Department = await _service.GetDepartmentAsync(_departmentId);
Guard the call as shown: the view reads the property many times while the load is in flight.
Change tracking with OnXChanged
OnXChanged hooks can record edits, for example to build a JSON Patch and send only what changed:
private JsonPatchDocument<CourseDto> patch = new();
partial void OnTitleChanged(string newValue) => patch.Replace(e => e.Title, newValue);
public async Task SubmitChanges()
{
Course = await _service.ModifyCourseAsync(_course.Id, patch.Operations);
patch.Operations.Clear();
}
Recommended practices
Negate in the view model, not in XAML. When the view needs the opposite of a property, add a get-only property that negates it, with [DependsOn]:
[DependsOn(nameof(NameIsValid))]
public bool NameIsInvalid => !NameIsValid;
[DependsOn(nameof(IsBusy))]
public bool IsIdle => !IsBusy;
No converter is needed and the logic can be unit-tested. Use one naming convention (XIsInvalid) everywhere.
Combine conditions in one computed property. Bind IsEnabled to a single property such as [DependsOn(nameof(IsBusy), nameof(IsValid))] public bool CanSave => !IsBusy && IsValid; instead of combining bindings in XAML.
Wrap the model, don't copy it. Hold the model in one [NotifyProperty] field and expose its members with [NotifyNestedProperty]. Rules stay on the model, and assigning a new model object refreshes the form.
Update forms: enable Save only after a change. Track edits with a flag set from the OnXChanged hooks:
[NotifyProperty]
private bool _changed;
partial void OnNameChanged(string newValue) => Changed = true;
partial void OnPhoneChanged(string? newValue) => Changed = true;
[DependsOn(nameof(Changed), nameof(IsValid), nameof(IsBusy))]
public bool CanUpdate => Changed && IsValid && !IsBusy;
Reset Changed = false at the end of the update task.
Required input without an error message. A property validator can return false with an empty message. The submit button stays disabled while the field is empty, but no error text appears, which suits a search box or a single-field form.
Multi-step pages: one state property. Model the steps as an enum in a single notified property, with computed booleans for the view:
public enum Step { Details, VerifyCode, Done }
[NotifyProperty]
private Step _step = Step.Details;
[DependsOn(nameof(Step))] public bool IsDetailsStep => Step == Step.Details;
[DependsOn(nameof(Step))] public bool IsVerifyCodeStep => Step == Step.VerifyCode;
[DependsOn(nameof(Step))] public bool IsDoneStep => Step == Step.Done;
Tasks move between steps by assigning Step, which pairs well with the "handle and report" error strategy.
One view model per list row. For lists whose rows have their own state or actions, give each row a small [ExtendViewModel] class with computed [DependsOn] properties.
Diagnostics
ViewModelPlus reports errors at build time. A member that breaks a rule is not generated, so these errors often come with follow-on "The name 'X' does not exist" errors. Fix the VM error first.
| Code | Cause | Fix |
|---|---|---|
| VM010 | [DependsOn] on a field without [NotifyProperty], or [NotifyNestedProperty] on a field whose type is not a class |
Add [NotifyProperty]; use nested properties only on class-type fields. |
| VM011 | [NotifyProperty] field is not private or protected |
Make it private. |
| VM013 | [NotifyProperty] field name starts with an uppercase letter |
Rename to _name or name. |
| VM014 | [NotifyNestedProperty] path does not exist, or [NotifyNestedProperty] / [AlsoNotify] used without [NotifyProperty] |
Check the path with nameof; add [NotifyProperty]. |
| VM015 | [NotifyTask] method is not private |
Make it private. |
| VM016 | [NotifyTask] method is not async |
Add async. |
| VM017 | [NotifyTask] method does not return Task / Task<T> |
Change the return type. |
| VM018 | [NotifyTask] method name starts with an uppercase letter |
Rename to save or _save. |
| VM019 | Validator method does not return bool |
Return bool. |
| VM020 | [PropertyValidator] target property does not exist |
Use nameof of the generated property. |
| VM021 | Property validator does not have exactly one parameter of the property's exact type | Match the type, including ?. |
| VM022 | [ModelValidator] method has parameters |
Remove them. |
| VM001, VM002, VM005, VM007, VM009 | An attribute's arguments could not be read | Pass compile-time constants (nameof, string literals) in the documented constructor forms. |
Limitations
Each row states what is not supported, what happens if you run into it, and what to do instead.
| Limitation | What happens | What to do |
|---|---|---|
| Dependencies are one level deep. | If C depends on B and B depends on A, changing A re-notifies B but not C. | List every original source on C: [DependsOn(nameof(A), nameof(B))]. |
| Changes made outside generated setters are not seen. | Writing a backing field, or a model member directly (_student.Email = "x"), changes the value but not the view or validation. |
Assign through the generated property, or call OnPropertyChanged(nameof(X)) and the trigger methods. |
| Assigning the current value does nothing. | The setter skips equal values, so Student = _student after editing its members, or X = _x to force re-validation, has no effect. |
Assign a new instance, or call OnPropertyChanged / TriggerXValidation() and TriggerModelValidation(). |
| A nested property change does not notify its base property. | A computed property that depends on Student is not refreshed when Email changes. |
Depend on the nested names: [DependsOn(nameof(Email))]. |
Nested properties under a nullable base reject null writes. |
While the base object is set, assigning null to one of its nested properties throws ValidationException("Value cannot be null"). |
Assign empty values ("", 0), or make the base field non-nullable. |
| Labels and descriptions are fields, not properties. | {Binding NameLabel} does not work in MAUI or WPF; WinUI x:Bind does. They are generated for every property, empty without [Display]. |
Expose a get-only property: public string NameCaption => NameLabel;. |
| Validation messages receive the value, not the field name. | {0} in an error message is replaced by the entered value; built-in messages read like "The field 7 must be between 1 and 5". |
Always set ErrorMessage (or the resource name) explicitly, without {0}. |
Only System.ComponentModel.DataAnnotations attributes are recognized. |
Custom ValidationAttribute subclasses declared in your own namespaces are ignored. |
Use a [PropertyValidator] method for custom rules. |
| Validation is synchronous. | Validators cannot await (for example, to check a value against a server). | Run the check in a [NotifyTask], store the result, then call the trigger methods. |
One [ModelValidator] per class. |
If several are declared, only the last is used, with no error. | Combine the rules in one method. |
No INotifyDataErrorInfo. |
Framework error visuals (for example WPF's Validation.ErrorTemplate) do not react. |
Bind XIsValid and XValidationError as shown in Showing validation in XAML. |
| Task exceptions are rethrown. | An exception not handled inside the task reaches the caller. | Map exceptions inside the task and catch at the call site (step 5). |
| Starting any task clears the page-level error. | AsyncTaskExceptionMessage describes the latest operation, so a task started by the page (for example a lazy load from OnGetX) hides an earlier error from another task. |
Show errors that must persist from the task's own XTaskExceptionMessage, which only that task changes. |
| Class shape is restricted. | Nested, generic, or non-public view-model classes, and classes outside a namespace, fail to compile. |
Use a top-level, non-generic, public partial class inside a namespace. |
| No inheritance between view models. | A view model deriving from another hides the base PropertyChanged event; base-class properties stop updating the view. |
Share code through composition or helper classes. |
| Class names must be unique per project. | Two view models with the same name in different namespaces produce conflicting generated files. | Give view models distinct names. |
| Not combinable with other MVVM generators on the same class. | Other toolkits that implement INotifyPropertyChanged declare the same members. |
Use one approach per class. |
Troubleshooting
"The name 'X' does not exist." Look for a VM error on the field or method; that member was not generated. Check that the class is public partial and inside a namespace. Field _x generates X, so use nameof(X), not nameof(_x).
The view does not update. See the first four rows of Limitations.
IsValid lags behind the fields. A rule's input changed outside a generated setter. Call TriggerXValidation(), then TriggerModelValidation().
The control never shows the invalid look. Check that its style defines a ValidationStates group with an "Invalid" state, that composite controls declare the group themselves, and that the attached property defaults to true.
An error disappears before the user reads it. Another task started and cleared AsyncTaskExceptionMessage. Bind that error to the failing task's own XTaskExceptionMessage instead.
An error message stays after a successful retry. The project uses a generator older than 1.1.88, which did not clear messages when a task starts. Upgrade the package.
IsBusy stays true. A task failed with HandleAsyncTaskExceptions = false. Turn the option back on.
Generated members do not appear in the editor. Build once; generated members appear after the generator runs. If they still do not appear, restart the IDE.
Internals
This section describes how the generated code behaves. You do not need it to use ViewModelPlus, but it explains the rules above.
Generated file
For each [ExtendViewModel] class, the generator emits ClassName.g.cs containing public partial class ClassName : INotifyPropertyChanged in the same namespace. It imports System, System.ComponentModel, System.ComponentModel.DataAnnotations, the class's namespace, and the namespaces of reference types used by the class's members. Because the file name is the bare class name, two classes with the same name in one project collide.
Setter pipeline
A generated setter for property X runs these steps:
- Return if
value == current(reference equality for classes without an==overload). - Call
OnXChanging(newValue, oldValue)andOnXChanging(newValue), then store the value. For nested properties under a nullable base, the store happens only when the base is notnull. - Raise
PropertyChanged("X"), thenPropertyChangedfor each property registered as dependent on X. - If
Validateis on: runTriggerXValidation()for X and for each of its nested properties that have rules, thenTriggerModelValidation(). - Call
OnXChanged(newValue, oldValue)andOnXChanged(newValue).
A getter calls OnGetBase() (for nested properties), then OnGetX(), then returns the value.
Dependency map
[DependsOn], [AlsoNotify], the nested-property declarations and their DependsOn / AlsoNotify arguments are merged at compile time into one map from a source name to the names to re-notify. Each source re-notifies only its direct entries; the map is not followed further, which is why dependencies are one level deep. Generated state properties use these source keys: IsValid, XIsValid, IsBusy, XIsRunning, AsyncTaskExceptionMessage, and XException for a task's own message.
Validation pipeline
TriggerXValidation():
- Sets
XValidationErrortonull. - Creates each DataAnnotations attribute declared on the field (or model member) with the same arguments, and calls
IsValid(value)in declaration order. The first failure setsXValidationError = attribute.FormatErrorMessage(value)and skips the remaining attributes. Passing the value toFormatErrorMessageis why{0}becomes the value. - If the attributes passed and a
[PropertyValidator]exists, calls it. - Caches the result. If it changed, raises
PropertyChanged("XIsValid")and notifies its dependents.
IsValid is the AND, in order, of each rule-bearing property's cached result (a property never evaluated is evaluated now), followed by the [ModelValidator] if all passed. Evaluation stops at the first invalid property. TriggerModelValidation() stores the result and, if it changed, raises PropertyChanged("IsValid"), notifies dependents of IsValid and raises IsValidChanged.
With EmptyFormInitialValidationState = true, a property's XIsValid returns true while it has no cached result, and IsValid starts as false. Computing IsValid can still evaluate an untouched property, filling its XValidationError without caching its XIsValid. That is why error labels should be shown based on XIsValid (through XIsInvalid), not on whether XValidationError has text.
Task wrapper
public async Task<T> X(args)
{
// a new run starts: clear errors of the previous run
if (__XTaskExceptionMessage != null) XTaskExceptionMessage = null;
if (__asyncTaskExceptionMessage != null) AsyncTaskExceptionMessage = null;
XIsRunning = true;
try
{
var result = await x(args);
XIsRunning = false;
return result;
}
catch (Exception ex)
{
XTaskExceptionMessage = ex.Message;
AsyncTaskExceptionMessage = ex.Message;
XIsRunning = false;
throw;
}
}
The messages are cleared only when they hold a value, so a run that follows a successful one raises no notifications for them. Setting any XIsRunning recomputes IsBusy as the OR of all of them. Setting AsyncTaskExceptionMessage also raises PropertyChanged("AsyncTaskErrorExists"). With HandleAsyncTaskExceptions = false the try/catch is omitted, so a failure skips XIsRunning = false.
Repository layout and packaging
| Folder | Contents |
|---|---|
ViewModelPlus/ |
The generator: Generator.cs (incremental pipeline and diagnostics), VMTemplate.tt (the T4 template of the generated class), ViewModelAnalyzer.cs, PropertyDescriptor.cs. |
ViewModelPlus.Annotations/ |
The attributes (Attributes.cs). |
TestViewModelPlus/ |
A sample console project that exercises the generator. |
Both projects create their NuGet package on every build (GeneratePackageOnBuild) with the version fixed in PackageVersion. NuGet caches packages by version, so bump PackageVersion for every change and update consuming projects. The IDE keeps a loaded generator in memory, so restart it after upgrading. To reuse a version number during development, clear the cache with dotnet nuget locals global-packages --clear.
Publishing. .github/workflows/ci.yml builds and packs both projects on every push and pull request to main. Publishing a GitHub Release runs .github/workflows/release.yml, which pushes both packages to nuget.org through Trusted Publishing (no API key stored). Annotations goes first because the generator package depends on it. A package whose PackageVersion already exists on nuget.org is skipped, so bump only the package(s) you changed before creating the release. TestViewModelPlus is not built in CI because it consumes the published packages.
Learn more about Target Frameworks and .NET Standard.
-
.NETStandard 2.0
- System.CodeDom (>= 9.0.4)
- ViewModelPlus.Annotations (>= 1.0.10)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.1.88 | 6 | 12/1/2026 |