MVVM Toolkit

MVVM Toolkit

Guides writing and reviewing MVVM view models with CommunityToolkit.Mvvm: source generators, commands, base classes and validation across WPF, WinUI, MAUI and more.

Skill files6 files

references/

SKILL.md295 lines
1
---
2
name: mvvm-toolkit
3
description: '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.'
4
---
5
6
# CommunityToolkit.Mvvm (core)
7
8
Use this skill when authoring or reviewing ViewModels, properties,
9
commands, or validation in apps that use `CommunityToolkit.Mvvm` 8.x.
10
11
> **Companion skills.** Load **`mvvm-toolkit-messenger`** for `IMessenger`
12
> pub/sub patterns. Load **`mvvm-toolkit-di`** for
13
> `Microsoft.Extensions.DependencyInjection` integration.
14
15
> **Quick recap.** `[ObservableProperty]` on private fields in `partial`
16
> classes; `[RelayCommand]` on instance methods; inherit from
17
> `ObservableObject` (or `ObservableValidator` for input forms,
18
> `ObservableRecipient` when using `IMessenger`).
19
20
---
21
22
## Package & setup
23
24
```xml
25
<ItemGroup>
26
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.*" />
27
</ItemGroup>
28
```
29
30
Targets: `netstandard2.0`, `netstandard2.1`, `net6.0`+. Works on .NET, .NET
31
Framework, Mono. Source generators ship in the same NuGet — no extra
32
analyzer reference required.
33
34
Namespaces:
35
36
```csharp
37
using CommunityToolkit.Mvvm.ComponentModel; // ObservableObject, [ObservableProperty]
38
using CommunityToolkit.Mvvm.Input; // [RelayCommand], RelayCommand, AsyncRelayCommand
39
```
40
41
> **Universal rule.** Every type that uses `[ObservableProperty]` or
42
> `[RelayCommand]` — and every enclosing type, if nested — must be
43
> declared `partial`. Without it, the generators emit
44
> `MVVMTK0008` / `MVVMTK0042`.
45
46
---
47
48
## Source generators cheat sheet
49
50
| Attribute | Applied to | Generates |
51
|-----------|-----------|-----------|
52
| `[ObservableProperty]` | private field | Public `INotifyPropertyChanged` property + `OnXxxChanging`/`OnXxxChanged` partial-method hooks |
53
| `[NotifyPropertyChangedFor(nameof(Other))]` | observable field | Also raises `PropertyChanged` for the listed property |
54
| `[NotifyCanExecuteChangedFor(nameof(MyCommand))]` | observable field | Calls `MyCommand.NotifyCanExecuteChanged()` on change |
55
| `[NotifyDataErrorInfo]` | observable field on `ObservableValidator` | Calls `ValidateProperty(value)` from the setter |
56
| `[NotifyPropertyChangedRecipients]` | observable field on `ObservableRecipient` | `Broadcast(old, new)` after the change |
57
| `[RelayCommand]` | instance method | Lazy `RelayCommand` / `AsyncRelayCommand` exposed as `IRelayCommand` / `IAsyncRelayCommand` |
58
| `[RelayCommand(CanExecute = nameof(CanX))]` | instance method | Wires `CanExecute` to a method or property |
59
| `[RelayCommand(IncludeCancelCommand = true)]` | async method with `CancellationToken` | Also generates `XxxCancelCommand` |
60
| `[RelayCommand(AllowConcurrentExecutions = true)]` | async method | Allows queued/parallel invocations (default disables while running) |
61
| `[RelayCommand(FlowExceptionsToTaskScheduler = true)]` | async method | Surfaces exceptions via `ExecutionTask` instead of awaiting and rethrowing |
62
| `[property: SomeAttr]` | observable field or `[RelayCommand]` method | Forwards `SomeAttr` onto the generated property (e.g., `[JsonIgnore]`) |
63
64
**Naming.** Field `name` / `_name` / `m_name` → `Name`. Method `LoadAsync` →
65
`LoadCommand` (the `Async` suffix is stripped; a leading `On` is also
66
stripped).
67
68
See [`references/source-generators.md`](references/source-generators.md) for
69
the full attribute reference with generated-code samples.
70
71
---
72
73
## ViewModel patterns
74
75
### Simple observable property
76
77
```csharp
78
public partial class ContactViewModel : ObservableObject
79
{
80
[ObservableProperty]
81
private string? name;
82
}
83
```
84
85
### Hooks: `OnXxxChanging` / `OnXxxChanged`
86
87
```csharp
88
[ObservableProperty]
89
private string? name;
90
91
partial void OnNameChanged(string? value) =>
92
Logger.LogInformation("Name changed to {Name}", value);
93
```
94
95
Both single-arg `(value)` and two-arg `(oldValue, newValue)` overloads
96
are available. Implement only the ones you need; unimplemented hooks are
97
elided by the compiler (zero runtime cost).
98
99
### Dependent properties + dependent commands
100
101
```csharp
102
[ObservableProperty]
103
[NotifyPropertyChangedFor(nameof(FullName))]
104
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
105
private string? firstName;
106
107
[ObservableProperty]
108
[NotifyPropertyChangedFor(nameof(FullName))]
109
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
110
private string? lastName;
111
112
public string FullName => $"{FirstName} {LastName}".Trim();
113
```
114
115
### Wrapping a non-observable model
116
117
```csharp
118
public sealed class ObservableUser(User user) : ObservableObject
119
{
120
public string Name
121
{
122
get => user.Name;
123
set => SetProperty(user.Name, value, user, (u, n) => u.Name = n);
124
}
125
}
126
```
127
128
Pass a static lambda (no captured state) to keep the call allocation-free.
129
130
---
131
132
## Commands
133
134
```csharp
135
[RelayCommand]
136
private void Refresh() => Items.Reset();
137
138
[RelayCommand]
139
private async Task LoadAsync()
140
{
141
foreach (var item in await service.GetItemsAsync())
142
Items.Add(item);
143
}
144
145
[RelayCommand(IncludeCancelCommand = true)]
146
private async Task DownloadAsync(CancellationToken token)
147
{
148
await using var stream = await http.GetStreamAsync(url, token);
149
// ...
150
}
151
152
[RelayCommand(CanExecute = nameof(CanSave))]
153
private Task SaveAsync() => repo.SaveAsync(Name!);
154
155
private bool CanSave() => !string.IsNullOrWhiteSpace(Name);
156
```
157
158
Reach for manual `RelayCommand` / `AsyncRelayCommand` constructors only
159
when you must own the command's lifetime explicitly or compose it from
160
non-trivial sources. The attribute style covers ~95% of cases.
161
162
See [`references/relaycommand-cookbook.md`](references/relaycommand-cookbook.md)
163
for sync / async / cancellable / concurrency / error-surfacing recipes.
164
165
---
166
167
## Base class selection
168
169
| Base class | Use when |
170
|------------|---------|
171
| `ObservableObject` | Default. `INotifyPropertyChanged` + `INotifyPropertyChanging` + `SetProperty` overloads + `SetPropertyAndNotifyOnCompletion` for `Task` properties |
172
| `ObservableValidator` | The VM needs `INotifyDataErrorInfo` (forms, settings input) |
173
| `ObservableRecipient` | The VM sends or receives `IMessenger` messages — see the **`mvvm-toolkit-messenger`** skill |
174
175
C# is single-inheritance: `ObservableValidator` and `ObservableRecipient`
176
both extend `ObservableObject`, so combining them requires composition
177
(e.g., inject `IMessenger` into an `ObservableValidator`).
178
179
---
180
181
## Validation
182
183
```csharp
184
using System.ComponentModel.DataAnnotations;
185
186
public sealed partial class RegistrationViewModel : ObservableValidator
187
{
188
[ObservableProperty]
189
[NotifyDataErrorInfo]
190
[Required, MinLength(2), MaxLength(100)]
191
private string? name;
192
193
[ObservableProperty]
194
[NotifyDataErrorInfo]
195
[Required, EmailAddress]
196
private string? email;
197
198
[RelayCommand]
199
private void Submit()
200
{
201
ValidateAllProperties();
202
if (HasErrors) return;
203
// submit...
204
}
205
}
206
```
207
208
Other entry points: `TrySetProperty`, `ValidateProperty(value, name)`,
209
`ClearAllErrors()`, `GetErrors(propertyName)`. Custom rules support
210
`[CustomValidation]` methods and custom `ValidationAttribute` subclasses.
211
212
See [`references/validation.md`](references/validation.md) for the full
213
validator surface area.
214
215
---
216
217
## Top pitfalls
218
219
1. **Forgetting `partial`.** Class (and every enclosing type) must be
220
`partial`. Compile error `MVVMTK0008` / `MVVMTK0042`.
221
2. **PascalCase field name.** `[ObservableProperty] private string Name;`
222
collides with the generated property. Use `name`, `_name`, or `m_name`.
223
3. **`async void` on `[RelayCommand]`.** The generator only wraps
224
`Task`-returning methods as `IAsyncRelayCommand`. `async void` becomes
225
a sync `RelayCommand` and exceptions are unobserved. Always return
226
`Task`.
227
4. **Forgetting `[NotifyCanExecuteChangedFor]`.** The Save button stays
228
disabled even though `CanSave()` would now return `true`.
229
5. **Mutating the same reference held by an `[ObservableProperty]`
230
field.** `EqualityComparer<T>.Default` returns `true`, no notification
231
fires. Replace the instance instead of mutating it.
232
233
For the full diagnostic table (`MVVMTK0xxx`) and more pitfalls, see
234
[`references/troubleshooting.md`](references/troubleshooting.md).
235
236
---
237
238
## End-to-end mini walkthrough
239
240
A two-pane Notes app demonstrating generators + commands +
241
`[NotifyCanExecuteChangedFor]`:
242
243
```csharp
244
public sealed partial class NoteViewModel(INotesService notes,
245
IMessenger messenger) : ObservableRecipient(messenger)
246
{
247
[ObservableProperty]
248
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
249
[NotifyCanExecuteChangedFor(nameof(DeleteCommand))]
250
private string? filename;
251
252
[ObservableProperty]
253
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
254
private string? text;
255
256
[RelayCommand(CanExecute = nameof(CanSave))]
257
private Task SaveAsync()
258
{
259
Messenger.Send(new NoteSavedMessage(Filename!));
260
return notes.SaveAsync(Filename!, Text!);
261
}
262
263
[RelayCommand(CanExecute = nameof(CanDelete))]
264
private Task DeleteAsync() => notes.DeleteAsync(Filename!);
265
266
private bool CanSave() =>
267
!string.IsNullOrWhiteSpace(Filename) && !string.IsNullOrEmpty(Text);
268
private bool CanDelete() => !string.IsNullOrWhiteSpace(Filename);
269
}
270
```
271
272
For the full sample (DI wiring, View code-behind, XAML, unit tests), see
273
[`references/end-to-end-walkthrough.md`](references/end-to-end-walkthrough.md).
274
275
---
276
277
## References & companion skills
278
279
| Topic | Where |
280
|-------|-------|
281
| Source generator attribute reference | [`references/source-generators.md`](references/source-generators.md) |
282
| RelayCommand recipes | [`references/relaycommand-cookbook.md`](references/relaycommand-cookbook.md) |
283
| Validation deep dive | [`references/validation.md`](references/validation.md) |
284
| Full Notes-app walkthrough | [`references/end-to-end-walkthrough.md`](references/end-to-end-walkthrough.md) |
285
| `MVVMTK0xxx` diagnostics & pitfalls | [`references/troubleshooting.md`](references/troubleshooting.md) |
286
| **Messenger pub/sub** | Companion skill: **`mvvm-toolkit-messenger`** |
287
| **`Microsoft.Extensions.DependencyInjection` wiring** | Companion skill: **`mvvm-toolkit-di`** |
288
289
External sources:
290
291
- Toolkit overview: <https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/>
292
- WinUI MVVM Toolkit tutorial: <https://learn.microsoft.com/en-us/windows/apps/tutorials/winui-mvvm-toolkit/intro>
293
- Source: <https://github.com/CommunityToolkit/dotnet>
294
- Samples: <https://github.com/CommunityToolkit/MVVM-Samples>
295

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…