Generated banner for Mvvm Toolkit
Generated logo for Mvvm Toolkit

Mvvm Toolkit

GitHubOfficialFirst committed by alvinashcraftDistributed by GitHub

  • Skill
  • Tool integration
  • Software development
  • MIT
  • No issues found

From the author

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.
— the description by alvinashcraft

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The CommunityToolkit.Mvvm provides a set of core components for building applications using the Model-View-ViewModel (MVVM) pattern. It includes source generators to reduce boilerplate code for properties and commands, along with base classes for managing observable objects, validation, and messaging. The toolkit is designed to work across various .NET UI frameworks including WPF, WinUI 3, MAUI, Uno, and Avalonia.

What it does

  • Generates boilerplate code for observable properties and commands via attributes.
  • Provides base classes like ObservableObject, ObservableValidator, and ObservableRecipient.
  • Supports input validation through DataAnnotations and INotifyDataErrorInfo.
  • Facilitates command execution with RelayCommand and AsyncRelayCommand.
  • Enables property change notifications and dependency tracking between properties.
  • Integrates with .NET dependency injection and messaging patterns.

When to use it

  • When developing applications using the MVVM pattern in .NET.
  • When you need to reduce manual implementation of INotifyPropertyChanged.
  • When building forms that require input validation.
  • When you need to manage command execution states in your ViewModels.
  • When working with cross-platform UI frameworks like MAUI, Avalonia, or WinUI 3.

Advantages

  • Reduces boilerplate code through source generation.
  • Provides consistent base classes for ViewModel architecture.
  • Supports asynchronous command execution with built-in cancellation and status tracking.
  • Integrates seamlessly with standard .NET patterns and dependency injection.
  • Works across multiple .NET UI frameworks.

Usage examples

“How do I create an observable property in my ViewModel?”
Use the [ObservableProperty] attribute on a private field within a partial class to automatically generate a public property with change notification.
“How can I create a command that runs asynchronously?”
Apply the [RelayCommand] attribute to an async method returning a Task to generate an IAsyncRelayCommand.
“How do I validate properties in my ViewModel?”
Inherit from ObservableValidator and use DataAnnotation attributes like [Required] or [EmailAddress] alongside the [NotifyDataErrorInfo] attribute.
“How do I update a command's enabled state when a property changes?”
Use the [NotifyCanExecuteChangedFor(nameof(CommandName))] attribute on the observable field that should trigger the re-evaluation.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/github/mvvm-toolkit/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip mvvm-toolkit.zip -d .agents/skills

Documentation by alvinashcraft

CommunityToolkit.Mvvm (core)

Use this skill when authoring or reviewing ViewModels, properties, commands, or validation in apps that use CommunityToolkit.Mvvm 8.x.

Companion skills. Load mvvm-toolkit-messenger for IMessenger pub/sub patterns. Load mvvm-toolkit-di for Microsoft.Extensions.DependencyInjection integration.

Quick recap. [ObservableProperty] on private fields in partial classes; [RelayCommand] on instance methods; inherit from ObservableObject (or ObservableValidator for input forms, ObservableRecipient when using IMessenger).


Package & setup

<ItemGroup>
  <PackageReference Include="CommunityToolkit.Mvvm" Version="8.*" />
</ItemGroup>

Targets: netstandard2.0, netstandard2.1, net6.0+. Works on .NET, .NET Framework, Mono. Source generators ship in the same NuGet — no extra analyzer reference required.

Namespaces:

using CommunityToolkit.Mvvm.ComponentModel;   // ObservableObject, [ObservableProperty]
using CommunityToolkit.Mvvm.Input;             // [RelayCommand], RelayCommand, AsyncRelayCommand

Universal rule. Every type that uses [ObservableProperty] or [RelayCommand] — and every enclosing type, if nested — must be declared partial. Without it, the generators emit MVVMTK0008 / MVVMTK0042.


Source generators cheat sheet

AttributeApplied toGenerates
[ObservableProperty]private fieldPublic INotifyPropertyChanged property + OnXxxChanging/OnXxxChanged partial-method hooks
[NotifyPropertyChangedFor(nameof(Other))]observable fieldAlso raises PropertyChanged for the listed property
[NotifyCanExecuteChangedFor(nameof(MyCommand))]observable fieldCalls MyCommand.NotifyCanExecuteChanged() on change
[NotifyDataErrorInfo]observable field on ObservableValidatorCalls ValidateProperty(value) from the setter
[NotifyPropertyChangedRecipients]observable field on ObservableRecipientBroadcast(old, new) after the change
[RelayCommand]instance methodLazy RelayCommand / AsyncRelayCommand exposed as IRelayCommand / IAsyncRelayCommand
[RelayCommand(CanExecute = nameof(CanX))]instance methodWires CanExecute to a method or property
[RelayCommand(IncludeCancelCommand = true)]async method with CancellationTokenAlso generates XxxCancelCommand
[RelayCommand(AllowConcurrentExecutions = true)]async methodAllows queued/parallel invocations (default disables while running)
[RelayCommand(FlowExceptionsToTaskScheduler = true)]async methodSurfaces exceptions via ExecutionTask instead of awaiting and rethrowing
[property: SomeAttr]observable field or [RelayCommand] methodForwards SomeAttr onto the generated property (e.g., [JsonIgnore])

Naming. Field name / _name / m_name → Name. Method LoadAsync → LoadCommand (the Async suffix is stripped; a leading On is also stripped).

See references/source-generators.md for the full attribute reference with generated-code samples.


ViewModel patterns

Simple observable property
public partial class ContactViewModel : ObservableObject
{
    [ObservableProperty]
    private string? name;
}
Hooks: OnXxxChanging / OnXxxChanged
[ObservableProperty]
private string? name;

partial void OnNameChanged(string? value) =>
    Logger.LogInformation("Name changed to {Name}", value);

Both single-arg (value) and two-arg (oldValue, newValue) overloads are available. Implement only the ones you need; unimplemented hooks are elided by the compiler (zero runtime cost).

Dependent properties + dependent commands
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
private string? firstName;

[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
private string? lastName;

public string FullName => $"{FirstName} {LastName}".Trim();
Wrapping a non-observable model
public sealed class ObservableUser(User user) : ObservableObject
{
    public string Name
    {
        get => user.Name;
        set => SetProperty(user.Name, value, user, (u, n) => u.Name = n);
    }
}

Pass a static lambda (no captured state) to keep the call allocation-free.


Commands

[RelayCommand]
private void Refresh() => Items.Reset();

[RelayCommand]
private async Task LoadAsync()
{
    foreach (var item in await service.GetItemsAsync())
        Items.Add(item);
}

[RelayCommand(IncludeCancelCommand = true)]
private async Task DownloadAsync(CancellationToken token)
{
    await using var stream = await http.GetStreamAsync(url, token);
    // ...
}

[RelayCommand(CanExecute = nameof(CanSave))]
private Task SaveAsync() => repo.SaveAsync(Name!);

private bool CanSave() => !string.IsNullOrWhiteSpace(Name);

Reach for manual RelayCommand / AsyncRelayCommand constructors only when you must own the command's lifetime explicitly or compose it from non-trivial sources. The attribute style covers ~95% of cases.

See references/relaycommand-cookbook.md for sync / async / cancellable / concurrency / error-surfacing recipes.


Base class selection

Base classUse when
ObservableObjectDefault. INotifyPropertyChanged + INotifyPropertyChanging + SetProperty overloads + SetPropertyAndNotifyOnCompletion for Task properties
ObservableValidatorThe VM needs INotifyDataErrorInfo (forms, settings input)
ObservableRecipientThe VM sends or receives IMessenger messages — see the mvvm-toolkit-messenger skill

C# is single-inheritance: ObservableValidator and ObservableRecipient both extend ObservableObject, so combining them requires composition (e.g., inject IMessenger into an ObservableValidator).


Validation

using System.ComponentModel.DataAnnotations;

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

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

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

Other entry points: TrySetProperty, ValidateProperty(value, name), ClearAllErrors(), GetErrors(propertyName). Custom rules support [CustomValidation] methods and custom ValidationAttribute subclasses.

See references/validation.md for the full validator surface area.


Top pitfalls

  1. Forgetting partial. Class (and every enclosing type) must be partial. Compile error MVVMTK0008 / MVVMTK0042.

  2. PascalCase field name. [ObservableProperty] private string Name; collides with the generated property. Use name, _name, or m_name.

  3. async void on [RelayCommand]. The generator only wraps Task-returning methods as IAsyncRelayCommand. async void becomes a sync RelayCommand and exceptions are unobserved. Always return Task.

  4. Forgetting [NotifyCanExecuteChangedFor]. The Save button stays disabled even though CanSave() would now return true.

  5. Mutating the same reference held by an [ObservableProperty] field. EqualityComparer<T>.Default returns true, no notification fires. Replace the instance instead of mutating it.

For the full diagnostic table (MVVMTK0xxx) and more pitfalls, see references/troubleshooting.md.


End-to-end mini walkthrough

A two-pane Notes app demonstrating generators + commands + [NotifyCanExecuteChangedFor]:

public sealed partial class NoteViewModel(INotesService notes,
    IMessenger messenger) : ObservableRecipient(messenger)
{
    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(SaveCommand))]
    [NotifyCanExecuteChangedFor(nameof(DeleteCommand))]
    private string? filename;

    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(SaveCommand))]
    private string? text;

    [RelayCommand(CanExecute = nameof(CanSave))]
    private Task SaveAsync()
    {
        Messenger.Send(new NoteSavedMessage(Filename!));
        return notes.SaveAsync(Filename!, Text!);
    }

    [RelayCommand(CanExecute = nameof(CanDelete))]
    private Task DeleteAsync() => notes.DeleteAsync(Filename!);

    private bool CanSave() =>
        !string.IsNullOrWhiteSpace(Filename) && !string.IsNullOrEmpty(Text);
    private bool CanDelete() => !string.IsNullOrWhiteSpace(Filename);
}

For the full sample (DI wiring, View code-behind, XAML, unit tests), see references/end-to-end-walkthrough.md.


References & companion skills

TopicWhere
Source generator attribute referencereferences/source-generators.md
RelayCommand recipesreferences/relaycommand-cookbook.md
Validation deep divereferences/validation.md
Full Notes-app walkthroughreferences/end-to-end-walkthrough.md
MVVMTK0xxx diagnostics & pitfallsreferences/troubleshooting.md
Messenger pub/subCompanion skill: mvvm-toolkit-messenger
Microsoft.Extensions.DependencyInjection wiringCompanion skill: mvvm-toolkit-di

External sources:

Files

references/source-generators.md

Source generators reference

Complete attribute reference for CommunityToolkit.Mvvm 8.x source generators, with the code each one produces.

Universal rule. Every type that uses one of these attributes — and every enclosing type, if nested — must be declared partial. The generators emit a sibling partial class declaration; without partial, the compiler reports MVVMTK0008 / MVVMTK0042.


[ObservableProperty]

Generates an observable property from a private field.

using CommunityToolkit.Mvvm.ComponentModel;

public partial class SampleViewModel : ObservableObject
{
    [ObservableProperty]
    private string? name;
}

Generated (simplified):

public string? Name
{
    get => name;
    set
    {
        if (!EqualityComparer<string?>.Default.Equals(name, value))
        {
            string? oldValue = name;
            OnNameChanging(value);
            OnNameChanging(oldValue, value);
            OnPropertyChanging();
            name = value;
            OnNameChanged(value);
            OnNameChanged(oldValue, value);
            OnPropertyChanged();
        }
    }
}

partial void OnNameChanging(string? value);
partial void OnNameChanging(string? oldValue, string? newValue);
partial void OnNameChanged(string? value);
partial void OnNameChanged(string? oldValue, string? newValue);
Naming
  • Field name → property Name

  • Field _name → property Name

  • Field m_name → property Name

  • Field Name (PascalCase) → error (collides with generated property)

Hooks

Implement any subset of the partial methods. Unimplemented hooks are elided by the compiler — zero runtime cost.

[ObservableProperty]
private ChildViewModel? selectedItem;

partial void OnSelectedItemChanging(ChildViewModel? oldValue, ChildViewModel? newValue)
{
    if (oldValue is not null) oldValue.IsSelected = false;
    if (newValue is not null) newValue.IsSelected = true;
}

The hook methods are partial with no body declaration — you cannot add an explicit accessibility (no public/private).


[NotifyPropertyChangedFor(nameof(Other))]

Raises PropertyChanged for additional properties when this field changes. Stack multiple attributes for multiple targets.

[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
[NotifyPropertyChangedFor(nameof(Initials))]
private string? firstName;

Use it for derived/computed properties:

public string FullName => $"{FirstName} {LastName}";
public string Initials => $"{FirstName?[0]}{LastName?[0]}";

[NotifyCanExecuteChangedFor(nameof(MyCommand))]

Calls MyCommand.NotifyCanExecuteChanged() when this field changes. The target must be an IRelayCommand (or IAsyncRelayCommand) property.

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
[NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
private string? name;

[RelayCommand(CanExecute = nameof(CanSave))]
private Task SaveAsync() => repo.SaveAsync(Name!);

private bool CanSave() => !string.IsNullOrWhiteSpace(Name);

MVVMTK0016 is raised if the target is not an accessible IRelayCommand property in the same type.


[NotifyDataErrorInfo]

Only valid in types that inherit from ObservableValidator. Adds a ValidateProperty(value) call inside the generated setter, so DataAnnotation validators run on every assignment.

using System.ComponentModel.DataAnnotations;

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

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

Only attributes that derive from ValidationAttribute are forwarded to the generated property. Other attributes are ignored unless you use [property: ] (see below).


[NotifyPropertyChangedRecipients]

Only valid in types that inherit from ObservableRecipient. Adds a Broadcast(oldValue, newValue) call after a successful set, sending a PropertyChangedMessage<T> to all recipients of the active IMessenger.

public partial class SelectionViewModel : ObservableRecipient
{
    [ObservableProperty]
    [NotifyPropertyChangedRecipients]
    private Item? selectedItem;
}

Subscribers can listen with:

WeakReferenceMessenger.Default.Register<SelectionViewModel, PropertyChangedMessage<Item>>(
    this,
    static (r, m) =>
    {
        if (m.PropertyName == nameof(SelectionViewModel.SelectedItem))
            r.Handle(m.NewValue);
    });

[RelayCommand]

Generates a lazy RelayCommand / AsyncRelayCommand from an instance method. Exposes it via the IRelayCommand / IAsyncRelayCommand interface.

[RelayCommand]
private void Refresh() => Items.Reset();
private RelayCommand? refreshCommand;
public IRelayCommand RefreshCommand =>
    refreshCommand ??= new RelayCommand(Refresh);
Naming
  • Refresh → RefreshCommand

  • OnRefresh → RefreshCommand (leading On stripped)

  • LoadAsync → LoadCommand (trailing Async stripped)

  • OnLoadAsync → LoadCommand (both stripped)

Sync with parameter
[RelayCommand]
private void GreetUser(User user) => Console.WriteLine($"Hello {user.Name}");

Generates IRelayCommand<User> GreetUserCommand (a typed command).

Async without cancellation
[RelayCommand]
private async Task GreetUserAsync()
{
    var user = await users.GetCurrentAsync();
    Console.WriteLine($"Hello {user.Name}");
}

Generates IAsyncRelayCommand GreetUserCommand backed by AsyncRelayCommand.

Async with cancellation
[RelayCommand]
private async Task GreetUserAsync(CancellationToken token)
{
    try
    {
        var user = await users.GetCurrentAsync(token);
        Console.WriteLine($"Hello {user.Name}");
    }
    catch (OperationCanceledException) { /* expected */ }
}

The toolkit propagates a CancellationToken to the wrapped method. Calling GreetUserCommand.Cancel() signals it.

IncludeCancelCommand = true

Generates a paired XxxCancelCommand whose CanExecute is wired to the underlying async command's IsRunning state — bind it to a Cancel button:

[RelayCommand(IncludeCancelCommand = true)]
private async Task DownloadAsync(CancellationToken token) { /* ... */ }
<Button Command="{x:Bind ViewModel.DownloadCommand}" Content="Download"/>
<Button Command="{x:Bind ViewModel.DownloadCancelCommand}" Content="Cancel"/>
CanExecute = nameof(MethodOrProperty)
[RelayCommand(CanExecute = nameof(CanGreetUser))]
private void GreetUser(User? user) => Console.WriteLine($"Hello {user!.Name}");

private bool CanGreetUser(User? user) => user is not null;

The CanExecute member is invoked initially when the command is bound, and again every time the command's NotifyCanExecuteChanged runs (use [NotifyCanExecuteChangedFor] to wire that automatically when bound state changes).

AllowConcurrentExecutions = true

Default is false: while an invocation is pending, the command reports itself as not executable. Setting true allows queued/parallel invocations.

[RelayCommand(AllowConcurrentExecutions = true)]
private async Task PingAsync() { /* fire-and-keep-going */ }

When the wrapped method takes a CancellationToken and concurrent execution is not allowed, requesting a new execution while one is pending cancels the prior token first.

FlowExceptionsToTaskScheduler = true

Default is await-and-rethrow (exceptions crash the app, mirroring sync commands). Setting true routes exceptions through ExecutionTask and TaskScheduler.UnobservedTaskException instead — useful when the UI binds to ExecutionTask.Status to render error states.

[RelayCommand(FlowExceptionsToTaskScheduler = true)]
private async Task LoadAsync(CancellationToken token) { /* ... */ }

[property: SomeAttribute(...)]

Forwards an attribute onto the generated property (for either [ObservableProperty] fields or [RelayCommand] methods).

[ObservableProperty]
[property: JsonRequired]
[property: JsonPropertyName("name")]
private string? username;

[RelayCommand]
[property: JsonIgnore]
private void GreetUser(User user) { /* ... */ }

Use this for serialization attributes ([JsonIgnore], [JsonPropertyName], [XmlElement]), data attributes ([Display(Name=...)]), or any other attribute that needs to live on the property/command instead of on the field/method.


[INotifyPropertyChanged] (class-level)

Use only when you can't inherit from ObservableObject (e.g., the type already inherits from a different base). Generates the INotifyPropertyChanged plumbing on the type itself.

using CommunityToolkit.Mvvm.ComponentModel;

[INotifyPropertyChanged]
public partial class MyControl : UserControl
{
    [ObservableProperty]
    private string? caption;
}

Prefer ObservableObject (or ObservableValidator / ObservableRecipient) inheritance whenever possible. The class-level attribute exists primarily for inheritance-locked scenarios such as custom controls and platform base types.

There is also [ObservableObject] (class-level) for the same purpose if you want the full SetProperty<T> API surface generated onto the type without inheritance.

Requirements and compatibility

Written for: GitHub Copilot

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

First committed by
GitHub avatar of alvinashcraftalvinashcraft
Publisher
GitHub (Official)
Distributed by
GitHub
Source
github/awesome-copilot · skills/mvvm-toolkit · commit 797337f
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Contributors
alvinashcraft

AutoGineer is not affiliated with or endorsed by alvinashcraft or GitHub.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download mvvm-toolkit.zip