{"kind":"AgentDefinition","metadata":{"namespace":"community","name":"mvvm-toolkit","version":"0.1.0"},"spec":{"agents_md":"---\ndescription: 'CommunityToolkit.Mvvm (MVVM Toolkit) coding conventions for ViewModels, commands, messaging, validation, and DI across WPF, WinUI 3, .NET MAUI, Uno Platform, and Avalonia.'\napplyTo: '**/*.cs, **/*.xaml, **/*.csproj'\n---\n\n# CommunityToolkit.Mvvm (MVVM Toolkit)\n\nThese rules apply whenever a project references `CommunityToolkit.Mvvm`.\nFor deep reference and end-to-end examples, load the `mvvm-toolkit` skill.\n\n## Package \u0026 language\n\n- Reference `CommunityToolkit.Mvvm` 8.x (or newer) in `.csproj`. Do not\n  install the legacy `Microsoft.Toolkit.Mvvm` (7.x) for new projects.\n- C# `LangVersion` must support source generators (default in modern SDKs).\n\n## ViewModel base class\n\n- Inherit ViewModels from `ObservableObject` by default.\n- Use `ObservableValidator` only when the ViewModel needs\n  `INotifyDataErrorInfo` (forms, settings, input validation).\n- Use `ObservableRecipient` only when the ViewModel sends or receives\n  `IMessenger` messages.\n- Never hand-implement `INotifyPropertyChanged` when one of the toolkit\n  base classes can be used. If the type cannot inherit from a toolkit base\n  (e.g., a custom control), apply the class-level `[ObservableObject]` or\n  `[INotifyPropertyChanged]` attribute instead.\n\n## Properties\n\n- Declare every type that uses `[ObservableProperty]` as `partial` (and\n  every enclosing type, if nested).\n- Apply `[ObservableProperty]` to private fields named `name`, `_name`, or\n  `m_name` — never PascalCase. Let the generator emit the public property.\n- Do not write manual `SetProperty(ref field, value)` boilerplate when the\n  field qualifies for `[ObservableProperty]`.\n- Use `[NotifyPropertyChangedFor(nameof(Derived))]` to raise change\n  notifications for derived/computed properties.\n- Use `[NotifyCanExecuteChangedFor(nameof(XxxCommand))]` so commands\n  re-evaluate `CanExecute` when their inputs change.\n- Implement `OnXxxChanging` / `OnXxxChanged` partial-method hooks for\n  side-effects on property changes — do not subscribe to your own\n  `PropertyChanged` event.\n- Use `[property: SomeAttribute]` to forward an attribute (e.g.,\n  `[JsonIgnore]`, `[JsonPropertyName(...)]`) onto the generated property.\n\n## Commands\n\n- Use `[RelayCommand]` on instance methods over manually constructed\n  `RelayCommand` / `AsyncRelayCommand` instances.\n- `[RelayCommand]` methods must return `void` or `Task` (or `Task\u003cT\u003e`).\n  Never use `async void` — exceptions become unobserved.\n- For cancellable async work, declare a `CancellationToken` parameter and\n  optionally set `IncludeCancelCommand = true` to expose a paired\n  `XxxCancelCommand`.\n- Use `CanExecute = nameof(...)` plus `[NotifyCanExecuteChangedFor]` on the\n  inputs to keep button enable/disable state in sync.\n- Default `AllowConcurrentExecutions` to `false` (the default). Only set\n  `true` when overlapping invocations are explicitly safe and intended.\n- Default error policy is await-and-rethrow. Only set\n  `FlowExceptionsToTaskScheduler = true` when the UI binds to\n  `ExecutionTask` to render error states.\n\n## Messaging\n\n- Default to `WeakReferenceMessenger.Default`. Only switch to\n  `StrongReferenceMessenger.Default` when profiling shows the messenger is\n  hot, and document the lifetime guarantees.\n- Register handlers with the `(recipient, message)` lambda form using the\n  `static` modifier — never capture `this` in the lambda.\n- Prefer `IRecipient\u003cTMessage\u003e` interfaces on `ObservableRecipient`\n  ViewModels so `RegisterAll(this)` wires everything automatically when\n  `IsActive = true`.\n- Set `IsActive = true` on activation (e.g., `OnNavigatedTo`) and\n  `IsActive = false` on deactivation (e.g., `OnNavigatedFrom`).\n- Inheritance is not considered when delivering messages — register each\n  concrete message type explicitly.\n- Use channel tokens (the `int` / `string` / `Guid` overloads) to scope\n  messages to a sub-system or window when more than one consumer would\n  otherwise collide.\n\n## Dependency injection\n\n- Use `Microsoft.Extensions.DependencyInjection` for service and ViewModel\n  registration. Prefer the .NET Generic Host\n  (`Host.CreateDefaultBuilder()`) so configuration, logging, and scope\n  validation are wired automatically.\n- Register services and ViewModels in the composition root (typically\n  `App.xaml.cs`). Resolve the page's root ViewModel from DI in the page\n  constructor or via the navigation framework.\n- Inject services and child ViewModels through constructors. Do not call\n  `Ioc.Default.GetService\u003cT\u003e()` from inside ViewModels, services, or any\n  type the DI container can construct.\n- Lifetimes:\n  - `AddSingleton\u003cT\u003e()` — shell/main-window VMs, settings, file/HTTP\n    services, the shared `IMessenger`.\n  - `AddTransient\u003cT\u003e()` — per-page or per-document VMs.\n  - `AddScoped\u003cT\u003e()` — only with explicit `IServiceScope` usage; rarely\n    needed in client apps.\n- Register `IMessenger` once\n  (`services.AddSingleton\u003cIMessenger\u003e(WeakReferenceMessenger.Default)`)\n  and inject it via `ObservableRecipient(messenger)` constructors.\n\n## Validation\n\n- Use `ObservableValidator` plus `[NotifyDataErrorInfo]` and DataAnnotation\n  attributes (`[Required]`, `[Range]`, `[EmailAddress]`, `[MinLength]`,\n  `[MaxLength]`, `[CustomValidation]`).\n- Call `ValidateAllProperties()` before submitting a form; check\n  `HasErrors` and bail out if `true`.\n- Reset error state with `ClearAllErrors()` after a successful submit or\n  when resetting a form.\n- For cross-property rules, call `ValidateProperty(value, nameof(Other))`\n  from the changed property's `OnXxxChanged` hook.\n\n## XAML\n\n- For WinUI 3 / UWP, prefer `{x:Bind}` (compiled bindings) over\n  `{Binding}`. Set `Mode=OneWay` or `Mode=TwoWay` explicitly — `{x:Bind}`\n  defaults to `OneTime`.\n- Bind `Command=\"{x:Bind ViewModel.SaveCommand}\"` directly to the\n  generated command property.\n- Bind async-command status (`IsRunning`, `ExecutionTask.Status`,\n  `ExecutionTask.Exception`) to surface progress/errors instead of\n  blocking the UI thread.\n\n## Things to avoid\n\n- `[ObservableProperty] private string Name;` — PascalCase field collides\n  with the generated property; use lowerCamel.\n- Manual `RaisePropertyChanged(nameof(X))` calls alongside\n  `[ObservableProperty]` — produces duplicate notifications.\n- `Ioc.Default.GetService\u003cT\u003e()` from inside a ViewModel constructor —\n  hides dependencies, breaks unit tests.\n- `StrongReferenceMessenger` without `OnDeactivated` / `UnregisterAll` —\n  pins recipients and leaks them.\n- Capturing `this` in messenger lambdas — closure allocation and\n  lifetime confusion. Always use `(r, m) =\u003e r.OnX(m)` with `static`.\n- `async void` on `[RelayCommand]` methods — return `Task` instead.\n- Mutating the same reference held by an `[ObservableProperty]` field —\n  the equality comparer returns `true` and no change notification fires.\n  Replace the instance instead.\n- Inheriting from both `ObservableValidator` and `ObservableRecipient` —\n  not possible; use composition (inject `IMessenger` or implement\n  validation manually).\n","description":"CommunityToolkit.Mvvm (MVVM Toolkit) coding conventions for ViewModels, commands, messaging, validation, and DI across WPF, WinUI 3, .NET MAUI, Uno Platform, and Avalonia.","import":{"commit_sha":"541b7819d8c3545c6df122491af4fa1eae415779","imported_at":"2026-05-18T20:05:35Z","license_text":"MIT License\n\nCopyright GitHub, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.","owner":"github","repo":"github/awesome-copilot","source_url":"https://github.com/github/awesome-copilot/blob/541b7819d8c3545c6df122491af4fa1eae415779/instructions/mvvm-toolkit.instructions.md"},"manifest":{}},"content_hash":[110,45,110,40,233,180,109,193,150,140,45,82,141,91,209,226,246,71,143,254,235,220,32,34,18,125,227,63,56,134,242,187],"trust_level":"unsigned","yanked":false}
