Mvvm Toolkit
GitHubOfficialFirst committed by alvinashcraftDistributed by GitHub
- Skill
- Tool integration
- Software development
- MIT
- No issues found
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/github/mvvm-toolkit/downloadUnzip 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-messengerforIMessengerpub/sub patterns. Loadmvvm-toolkit-diforMicrosoft.Extensions.DependencyInjectionintegration.
Quick recap.
[ObservableProperty]on private fields inpartialclasses;[RelayCommand]on instance methods; inherit fromObservableObject(orObservableValidatorfor input forms,ObservableRecipientwhen usingIMessenger).
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, AsyncRelayCommandUniversal rule. Every type that uses
[ObservableProperty]or[RelayCommand]— and every enclosing type, if nested — must be declaredpartial. Without it, the generators emitMVVMTK0008/MVVMTK0042.
Source generators cheat sheet
| Attribute | Applied to | Generates |
|---|---|---|
[ObservableProperty] | private field | Public INotifyPropertyChanged property + OnXxxChanging/OnXxxChanged partial-method hooks |
[NotifyPropertyChangedFor(nameof(Other))] | observable field | Also raises PropertyChanged for the listed property |
[NotifyCanExecuteChangedFor(nameof(MyCommand))] | observable field | Calls MyCommand.NotifyCanExecuteChanged() on change |
[NotifyDataErrorInfo] | observable field on ObservableValidator | Calls ValidateProperty(value) from the setter |
[NotifyPropertyChangedRecipients] | observable field on ObservableRecipient | Broadcast(old, new) after the change |
[RelayCommand] | instance method | Lazy RelayCommand / AsyncRelayCommand exposed as IRelayCommand / IAsyncRelayCommand |
[RelayCommand(CanExecute = nameof(CanX))] | instance method | Wires CanExecute to a method or property |
[RelayCommand(IncludeCancelCommand = true)] | async method with CancellationToken | Also generates XxxCancelCommand |
[RelayCommand(AllowConcurrentExecutions = true)] | async method | Allows queued/parallel invocations (default disables while running) |
[RelayCommand(FlowExceptionsToTaskScheduler = true)] | async method | Surfaces exceptions via ExecutionTask instead of awaiting and rethrowing |
[property: SomeAttr] | observable field or [RelayCommand] method | Forwards 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 class | Use when |
|---|---|
ObservableObject | Default. INotifyPropertyChanged + INotifyPropertyChanging + SetProperty overloads + SetPropertyAndNotifyOnCompletion for Task properties |
ObservableValidator | The VM needs INotifyDataErrorInfo (forms, settings input) |
ObservableRecipient | The 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
Forgetting
partial. Class (and every enclosing type) must bepartial. Compile errorMVVMTK0008/MVVMTK0042.PascalCase field name.
[ObservableProperty] private string Name;collides with the generated property. Usename,_name, orm_name.async voidon[RelayCommand]. The generator only wrapsTask-returning methods asIAsyncRelayCommand.async voidbecomes a syncRelayCommandand exceptions are unobserved. Always returnTask.Forgetting
[NotifyCanExecuteChangedFor]. The Save button stays disabled even thoughCanSave()would now returntrue.Mutating the same reference held by an
[ObservableProperty]field.EqualityComparer<T>.Defaultreturnstrue, 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
| Topic | Where |
|---|---|
| Source generator attribute reference | references/source-generators.md |
| RelayCommand recipes | references/relaycommand-cookbook.md |
| Validation deep dive | references/validation.md |
| Full Notes-app walkthrough | references/end-to-end-walkthrough.md |
MVVMTK0xxx diagnostics & pitfalls | references/troubleshooting.md |
| Messenger pub/sub | Companion skill: mvvm-toolkit-messenger |
Microsoft.Extensions.DependencyInjection wiring | Companion skill: mvvm-toolkit-di |
External sources:
Toolkit overview: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
WinUI MVVM Toolkit tutorial: https://learn.microsoft.com/en-us/windows/apps/tutorials/winui-mvvm-toolkit/intro
Files
- ATTRIBUTION.mdAdded by AutoGineer867 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md10.5 KiB
- references/end-to-end-walkthrough.md11.1 KiB
- references/relaycommand-cookbook.md6.7 KiB
- references/source-generators.md9.3 KiB
- references/troubleshooting.md7.0 KiB
- references/validation.md5.7 KiB
references/end-to-end-walkthrough.md
End-to-end walkthrough: WinUI 3 Notes app
A minimal Notes app demonstrating the full MVVM Toolkit story:
ObservableObject/ObservableRecipient, [ObservableProperty],
[RelayCommand], [NotifyCanExecuteChangedFor], WeakReferenceMessenger,
and Microsoft.Extensions.DependencyInjection.
This walkthrough mirrors the official tutorial at https://learn.microsoft.com/en-us/windows/apps/tutorials/winui-mvvm-toolkit/intro.
The same pattern works on WPF, MAUI, Uno, and Avalonia — only the XAML, navigation, and
Appbootstrap differ.
Project layout
MyApp/ ← WinUI 3 app project
App.xaml.cs
Views/
AllNotesPage.xaml
NotePage.xaml
MyApp.Shared/ ← .NET class library — ViewModels + services
ViewModels/
AllNotesViewModel.cs
NoteViewModel.cs
Services/
INotesService.cs
FileSystemNotesService.cs
Messages/
NoteSavedMessage.cs
NoteDeletedMessage.cs
MyApp.Tests/ ← xUnit / MSTest project — VM unit testsPutting ViewModels in a separate library is the recommended pattern: the library has no UI dependencies, so VMs are unit-testable in isolation.
1. The model
Plain POCO — no toolkit dependencies.
public sealed record NoteSummary(string Filename, string Preview, DateTime LastModified);2. The service
public interface INotesService
{
Task<IReadOnlyList<NoteSummary>> GetAllAsync();
Task<string> LoadAsync(string filename);
Task SaveAsync(string filename, string text);
Task DeleteAsync(string filename);
}
public sealed class FileSystemNotesService(string rootFolder) : INotesService
{
public async Task<IReadOnlyList<NoteSummary>> GetAllAsync()
{
var files = Directory.GetFiles(rootFolder, "*.txt");
var summaries = new List<NoteSummary>(files.Length);
foreach (var f in files)
{
var text = await File.ReadAllTextAsync(f);
summaries.Add(new NoteSummary(
Path.GetFileName(f),
text.Length > 60 ? text[..60] : text,
File.GetLastWriteTime(f)));
}
return summaries;
}
public Task<string> LoadAsync(string filename) =>
File.ReadAllTextAsync(Path.Combine(rootFolder, filename));
public Task SaveAsync(string filename, string text) =>
File.WriteAllTextAsync(Path.Combine(rootFolder, filename), text);
public Task DeleteAsync(string filename)
{
File.Delete(Path.Combine(rootFolder, filename));
return Task.CompletedTask;
}
}3. The messages
public sealed record NoteSavedMessage(string Filename);
public sealed record NoteDeletedMessage(string Filename);4. The list view model
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
public sealed partial class AllNotesViewModel : ObservableRecipient,
IRecipient<NoteSavedMessage>,
IRecipient<NoteDeletedMessage>
{
private readonly INotesService notes;
public AllNotesViewModel(INotesService notes, IMessenger messenger)
: base(messenger)
{
this.notes = notes;
IsActive = true; // start listening for messages
}
public ObservableCollection<NoteSummary> Notes { get; } = new();
[RelayCommand]
private async Task LoadAsync()
{
Notes.Clear();
foreach (var n in await notes.GetAllAsync())
Notes.Add(n);
}
public void Receive(NoteSavedMessage message) => _ = LoadAsync();
public void Receive(NoteDeletedMessage message) => _ = LoadAsync();
}ObservableRecipient's OnActivated (called when IsActive becomes
true) wires up the IRecipient<T> handlers automatically.
5. The editor view model
public sealed partial class NoteViewModel : ObservableRecipient
{
private readonly INotesService notes;
public NoteViewModel(INotesService notes, IMessenger messenger)
: base(messenger)
{
this.notes = notes;
}
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
[NotifyCanExecuteChangedFor(nameof(DeleteCommand))]
private string? filename;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
private string? text;
[RelayCommand]
private async Task LoadAsync(string filename)
{
Filename = filename;
Text = await notes.LoadAsync(filename);
}
[RelayCommand(CanExecute = nameof(CanSave))]
private async Task SaveAsync()
{
await notes.SaveAsync(Filename!, Text!);
Messenger.Send(new NoteSavedMessage(Filename!));
}
[RelayCommand(CanExecute = nameof(CanDelete))]
private async Task DeleteAsync()
{
await notes.DeleteAsync(Filename!);
Messenger.Send(new NoteDeletedMessage(Filename!));
Filename = null;
Text = null;
}
private bool CanSave() =>
!string.IsNullOrWhiteSpace(Filename) && !string.IsNullOrEmpty(Text);
private bool CanDelete() => !string.IsNullOrWhiteSpace(Filename);
}6. The composition root (App.xaml.cs)
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using CommunityToolkit.Mvvm.Messaging;
public partial class App : Application
{
public IHost Host { get; }
public App()
{
InitializeComponent();
var notesRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"MyApp", "notes");
Directory.CreateDirectory(notesRoot);
Host = Microsoft.Extensions.Hosting.Host
.CreateDefaultBuilder()
.ConfigureServices((_, services) =>
{
services.AddSingleton<INotesService>(_ => new FileSystemNotesService(notesRoot));
services.AddSingleton<IMessenger>(WeakReferenceMessenger.Default);
services.AddSingleton<AllNotesViewModel>();
services.AddTransient<NoteViewModel>();
})
.Build();
}
public static T GetService<T>() where T : class =>
((App)Current).Host.Services.GetRequiredService<T>();
}7. Wire up the views
AllNotesPage.xaml.cs:
public sealed partial class AllNotesPage : Page
{
public AllNotesViewModel ViewModel { get; } = App.GetService<AllNotesViewModel>();
public AllNotesPage()
{
InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
await ViewModel.LoadCommand.ExecuteAsync(null);
}
}AllNotesPage.xaml:
<Page x:Class="MyApp.Views.AllNotesPage"
xmlns:vm="using:MyApp.Shared.ViewModels">
<Grid RowDefinitions="Auto,*">
<CommandBar>
<AppBarButton Icon="Add" Label="New" Click="OnNewClicked"/>
<AppBarButton Icon="Refresh" Label="Refresh"
Command="{x:Bind ViewModel.LoadCommand}"/>
</CommandBar>
<ListView Grid.Row="1"
ItemsSource="{x:Bind ViewModel.Notes}"
ItemClick="OnNoteClicked"
IsItemClickEnabled="True">
<ListView.ItemTemplate>
<DataTemplate x:DataType="vm:NoteSummary">
<StackPanel>
<TextBlock Text="{x:Bind Filename}" FontWeight="SemiBold"/>
<TextBlock Text="{x:Bind Preview}"
TextTrimming="CharacterEllipsis"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Page>NotePage.xaml.cs:
public sealed partial class NotePage : Page
{
public NoteViewModel ViewModel { get; } = App.GetService<NoteViewModel>();
public NotePage()
{
InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.Parameter is string filename)
await ViewModel.LoadCommand.ExecuteAsync(filename);
ViewModel.IsActive = true;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
ViewModel.IsActive = false;
base.OnNavigatedFrom(e);
}
}NotePage.xaml:
<Page x:Class="MyApp.Views.NotePage">
<Grid RowDefinitions="Auto,*,Auto">
<TextBox Header="Filename" Text="{x:Bind ViewModel.Filename, Mode=TwoWay}"/>
<TextBox Grid.Row="1"
AcceptsReturn="True" TextWrapping="Wrap"
Text="{x:Bind ViewModel.Text, Mode=TwoWay}"/>
<StackPanel Grid.Row="2" Orientation="Horizontal" Spacing="8">
<Button Content="Save" Command="{x:Bind ViewModel.SaveCommand}"/>
<Button Content="Delete" Command="{x:Bind ViewModel.DeleteCommand}"/>
</StackPanel>
</Grid>
</Page>8. A representative unit test
using CommunityToolkit.Mvvm.Messaging;
public sealed class NoteViewModelTests
{
private sealed class FakeNotesService : INotesService
{
public List<(string filename, string text)> Saved { get; } = new();
public Task<IReadOnlyList<NoteSummary>> GetAllAsync() => Task.FromResult<IReadOnlyList<NoteSummary>>(Array.Empty<NoteSummary>());
public Task<string> LoadAsync(string filename) => Task.FromResult(string.Empty);
public Task SaveAsync(string filename, string text)
{
Saved.Add((filename, text));
return Task.CompletedTask;
}
public Task DeleteAsync(string filename) => Task.CompletedTask;
}
[Fact]
public async Task SaveCommand_persists_and_broadcasts()
{
var notes = new FakeNotesService();
var messenger = new WeakReferenceMessenger();
string? receivedFilename = null;
messenger.Register<NoteSavedMessage>(new object(), (_, m) => receivedFilename = m.Filename);
var vm = new NoteViewModel(notes, messenger)
{
Filename = "hello.txt",
Text = "world"
};
await vm.SaveCommand.ExecuteAsync(null);
Assert.Single(notes.Saved);
Assert.Equal("hello.txt", notes.Saved[0].filename);
Assert.Equal("world", notes.Saved[0].text);
Assert.Equal("hello.txt", receivedFilename);
}
}What to internalize from this sample
VMs go in a UI-free class library. The toolkit's only dependency is
netstandard2.0+, so VMs are testable without a UI host.Constructor injection everywhere. The composition root knows how to build everything; ViewModels and services receive their dependencies via parameters.
IMessengeris the cross-VM glue.WeakReferenceMessenger.Defaultis the right default. The list VM listens viaIRecipient<T>; the editor VM publishes viaMessenger.Send.[NotifyCanExecuteChangedFor]keeps Save/Delete buttons in sync with text input — no manual wiring needed.ObservableRecipient.IsActivecontrols subscription lifetime — set it fromOnNavigatedTo/OnNavigatedFrom(or an equivalent activation hook in your framework).
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
alvinashcraft
- 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