Index of every page on this site: llms.txt
All skills
github avatar

/mvvm-toolkit

@f10fdb8 official
by githubgithub/awesome-copilot42k stars
5,426
Run it yourself

CommunityToolkit.Mvvm (the MVVM Toolkit) core: source generators ([ObservableProperty], [RelayCommand], [NotifyPropertyChangedFor], [NotifyCanExecuteChangedFor], [NotifyDataErrorInfo]), base classes (ObservableObject / ObservableValidator / ObservableRecipient), commands (RelayCommand / AsyncRelayCommand), and validation. Companion skills: mvvm-toolkit-messenger for pub/sub, mvvm-toolkit-di for Microsoft.Extensions.DependencyInjection wiring. Works across WPF, WinUI 3, MAUI, Uno, and Avalonia.

Use this Skill: https://skilld.dev/gh/github/awesome-copilot/mvvm-toolkit

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesvalidation.md

≈1.5k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Validation with ObservableValidator

ObservableValidator extends ObservableObject with INotifyDataErrorInfo support, integrating with System.ComponentModel.DataAnnotations validation attributes.


Quick start

using System.ComponentModel.DataAnnotations;
using CommunityToolkit.Mvvm.ComponentModel;

public sealed partial class RegistrationViewModel : ObservableValidator
{
    [ObservableProperty]
    [NotifyDataErrorInfo]
    [Required]
    [MinLength(2), MaxLength(100)]
    private string? name;

    [ObservableProperty]
    [NotifyDataErrorInfo]
    [Required, EmailAddress]
    private string? email;

    [ObservableProperty]
    [NotifyDataErrorInfo]
    [Range(13, 120)]
    private int age;

    [RelayCommand]
    private void Submit()
    {
        ValidateAllProperties();
        if (HasErrors) return;
        // submit...
    }
}

[NotifyDataErrorInfo] makes the generated setter call ValidateProperty(value) after each successful set, so validation runs as the user types.


Manual SetProperty validation

If you write the property by hand instead of using [ObservableProperty], opt into validation with the bool validate parameter:

[Required, MinLength(2), MaxLength(100)]
public string? Name
{
    get => name;
    set => SetProperty(ref name, value, validate: true);
}

TrySetProperty

Sometimes you want to set a property only if validation succeeds:

[Required, EmailAddress]
public string? Email
{
    get => email;
    set
    {
        if (TrySetProperty(ref email, value, out IReadOnlyCollection<ValidationResult> errors))
        {
            // value passed validation; success
        }
        else
        {
            // inspect errors
        }
    }
}

ValidateAllProperties()

Forces validation across every public property in the type that has at least one ValidationAttribute. Call before submission:

[RelayCommand(CanExecute = nameof(CanSubmit))]
private void Submit()
{
    ValidateAllProperties();
    if (HasErrors) return;
    submitter.Submit(this);
}

private bool CanSubmit() => !HasErrors;

Pair with [NotifyCanExecuteChangedFor] on the input fields, plus a listener on ErrorsChanged (or override OnErrorsChanged) to keep the button state in sync as the user types.


ValidateProperty(value, propertyName)

Trigger validation manually for one property — useful when validation of property A depends on property B:

[Range(20, 80)]
[ObservableProperty]
private int b;

[Range(10, 100)]
[GreaterThan(nameof(B))]
[ObservableProperty]
private int a;

partial void OnBChanged(int value)
{
    // Re-run A's validation since it depends on B.
    ValidateProperty(A, nameof(A));
}

ClearAllErrors()

Reset the error state — common after a successful submit or when resetting a form:

[RelayCommand]
private void Reset()
{
    Name = null;
    Email = null;
    Age = 0;
    ClearAllErrors();
}

Custom validation method ([CustomValidation])

[Required, MinLength(3)]
[CustomValidation(typeof(RegistrationViewModel), nameof(ValidateUsername))]
[ObservableProperty]
private string? username;

public static ValidationResult ValidateUsername(string? value, ValidationContext context)
{
    var vm = (RegistrationViewModel)context.ObjectInstance;
    if (vm.userService.IsTaken(value!))
        return new ValidationResult("Username is already taken.");
    return ValidationResult.Success!;
}

The method must be static and accept (value, ValidationContext). Use context.ObjectInstance to reach back into the ViewModel.


Custom ValidationAttribute

For reusable rules, subclass ValidationAttribute:

public sealed class GreaterThanAttribute(string otherPropertyName)
    : ValidationAttribute
{
    public string OtherPropertyName { get; } = otherPropertyName;

    protected override ValidationResult? IsValid(object? value, ValidationContext ctx)
    {
        var instance = ctx.ObjectInstance;
        var other = instance.GetType().GetProperty(OtherPropertyName)?.GetValue(instance);
        if (((IComparable)value!).CompareTo(other) > 0)
            return ValidationResult.Success;
        return new ValidationResult($"Must be greater than {OtherPropertyName}.");
    }
}

Apply to the property:

[Range(10, 100)]
[GreaterThan(nameof(B))]
[ObservableProperty]
private int a;

Reading errors in the View

ObservableValidator implements INotifyDataErrorInfo. XAML stacks render ErrorsChanged automatically when ValidatesOnNotifyDataErrors=True (WPF) or via control templates (WinUI 3, MAUI). To inspect errors in code:

foreach (ValidationResult result in vm.GetErrors(nameof(vm.Name)))
{
    Console.WriteLine(result.ErrorMessage);
}

// Across all properties
foreach (ValidationResult result in vm.GetErrors())
{
    Console.WriteLine(result.ErrorMessage);
}

bool any = vm.HasErrors;

Subscribe to changes:

vm.ErrorsChanged += (s, e) =>
{
    Debug.WriteLine($"Errors changed for {e.PropertyName}");
};

Tips

  • Combine ValidateAllProperties() with [NotifyCanExecuteChangedFor] so the Submit button reflects validity in real time.
  • Keep validation rules in the ViewModel (or via custom attributes), not in the model — the model should be a plain DTO.
  • For network or async validation (e.g., "is username taken?"), use [CustomValidation] calling a synchronous wrapper around an async lookup (or perform the async check separately and surface the result via AddError(propertyName, ...)-style helpers if you write your own).
  • ObservableValidator cannot also inherit from ObservableRecipient — if you need messaging, inject IMessenger and call Send directly.

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

1 warning2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    This skill provides documentation and code templates for using the .NET CommunityToolkit.Mvvm library. It covers MVVM patterns, source generators, and validation. All code snippets follow standard development practices, and all external links point to trusted official Microsoft or Community Toolkit resources. No security issues were detected.

  • Socket2mo

    1 alert: gptAnomaly

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at f10fdb8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 days ago.

Activeupdated 7 months ago
  • csharp
  • mvvm
  • observable-property
  • relay-command
  • wpf
  • winui
  • maui
  • avalonia
  • validation
  • source-generators

README badge

README badge for github/awesome-copilot/mvvm-toolkit

Provides source generators and base classes for the MVVM Toolkit library: `[ObservableProperty]` for properties, `[RelayCommand]` for commands, `ObservableObject` / `ObservableValidator` / `ObservableRecipient` base classes, and validation via `INotifyDataErrorInfo`. Targets WPF, WinUI 3, MAUI, Uno, and Avalonia apps using CommunityToolkit.Mvvm 8.x.

Generated from the current SKILL.md.

Does this work with WPF, WinUI, MAUI, and Avalonia?
Yes. The MVVM Toolkit supports WPF, WinUI 3, MAUI, Uno, and Avalonia across netstandard2.0, netstandard2.1, and net6.0+.
Do I need to declare classes as partial?
Yes. Every class using [ObservableProperty] or [RelayCommand], and every enclosing type if nested, must be declared partial. Omitting it triggers compiler error MVVMTK0008 or MVVMTK0042.
How do I wire up dependent properties and commands that need to update when an observable field changes?
Use [NotifyPropertyChangedFor(nameof(...))] to propagate PropertyChanged to dependent properties, and [NotifyCanExecuteChangedFor(nameof(...))] to notify commands that their CanExecute state may have changed.
What do I use for form validation?
Inherit from ObservableValidator instead of ObservableObject, apply [NotifyDataErrorInfo] and validation attributes like [Required] and [EmailAddress] to observable fields, then call ValidateAllProperties() and check HasErrors.
Are there companion skills for messaging and dependency injection?
Yes. Load mvvm-toolkit-messenger for IMessenger pub/sub patterns, and mvvm-toolkit-di for Microsoft.Extensions.DependencyInjection integration.

Generated from the current SKILL.md. These answers refresh after source changes.