MVVM Toolkit Messenger

MVVM Toolkit Messenger

Teaches the AI how to use the CommunityToolkit.Mvvm Messenger for decoupled pub/sub between ViewModels across WPF, WinUI, MAUI and Avalonia apps.

Skill files2 files

references/

SKILL.md269 lines
1
---
2
name: mvvm-toolkit-messenger
3
description: 'CommunityToolkit.Mvvm Messenger pub/sub for decoupled communication between ViewModels (or any objects). Covers WeakReferenceMessenger vs StrongReferenceMessenger, IRecipient<TMessage>, RequestMessage<T> / AsyncRequestMessage<T> / CollectionRequestMessage<T>, ValueChangedMessage<T>, channels (tokens), and the ObservableRecipient activation lifecycle. Use across WPF, WinUI 3, .NET MAUI, Uno, and Avalonia.'
4
---
5
6
# CommunityToolkit.Mvvm Messenger
7
8
Pub/sub messaging for ViewModels (or any objects) without forcing a shared
9
reference graph. Part of `CommunityToolkit.Mvvm` 8.x.
10
11
> **TL;DR.** Default to `WeakReferenceMessenger.Default`. Register handlers
12
> with the `(recipient, message)` lambda and the `static` modifier so you
13
> never capture `this`. Inherit from `ObservableRecipient` and toggle
14
> `IsActive` at activation/deactivation to get automatic register/unregister.
15
16
---
17
18
## When to use this skill
19
20
- Two or more ViewModels need to react to an event (login, theme change,
21
save, navigation) without holding references to each other
22
- A ViewModel needs to ask another VM for a value (request/reply)
23
- You're scoping events to a sub-system or window with channel tokens
24
- Diagnosing "my handler never fires" or weak-reference recipient lifetime
25
problems
26
27
For source generators, base classes, and commands see the **`mvvm-toolkit`**
28
skill. For DI wiring (registering an `IMessenger` instance), see
29
**`mvvm-toolkit-di`**.
30
31
---
32
33
## Choose an implementation
34
35
| Type | When |
36
|------|------|
37
| `WeakReferenceMessenger.Default` | **Default.** Recipients held weakly — eligible for GC even while registered. Internal trimming runs during full GCs; no manual `Cleanup()` needed. |
38
| `StrongReferenceMessenger.Default` | Profiler shows the messenger is hot and allocation matters. Recipients are pinned until you `Unregister`. Forgetting unregistration leaks them. |
39
| Custom `IMessenger` instance | Per-window/per-scope (e.g., one messenger per app window). Construct directly, inject via DI. |
40
41
`ObservableRecipient`'s parameterless constructor uses
42
`WeakReferenceMessenger.Default`. Pass a different `IMessenger` to its
43
constructor to override.
44
45
---
46
47
## Define a message
48
49
The toolkit ships base classes; any class works.
50
51
```csharp
52
using CommunityToolkit.Mvvm.Messaging.Messages;
53
54
// Single-payload broadcast
55
public sealed class LoggedInUserChangedMessage(User user)
56
: ValueChangedMessage<User>(user);
57
58
// Custom shape (records are great for this)
59
public sealed record ThemeChangedMessage(AppTheme NewTheme);
60
61
// Empty signal
62
public sealed record RefreshRequestedMessage;
63
```
64
65
---
66
67
## Register a recipient
68
69
### Lambda style (recommended)
70
71
```csharp
72
WeakReferenceMessenger.Default.Register<MyViewModel, ThemeChangedMessage>(
73
this,
74
static (recipient, message) => recipient.OnThemeChanged(message.NewTheme));
75
```
76
77
The `static` modifier prevents accidental closure allocation and keeps
78
`this` out of the lambda — use the `recipient` parameter instead.
79
80
### `IRecipient<TMessage>` interface style
81
82
```csharp
83
public sealed class MyViewModel : ObservableRecipient,
84
IRecipient<ThemeChangedMessage>,
85
IRecipient<RefreshRequestedMessage>
86
{
87
public void Receive(ThemeChangedMessage message) { /* ... */ }
88
public void Receive(RefreshRequestedMessage message) { /* ... */ }
89
}
90
```
91
92
`ObservableRecipient.OnActivated()` calls `Messenger.RegisterAll(this)`,
93
which subscribes every `IRecipient<T>` interface implemented by the type.
94
If you're not using `ObservableRecipient`, register manually:
95
96
```csharp
97
WeakReferenceMessenger.Default.RegisterAll(this);
98
```
99
100
---
101
102
## Send a message
103
104
```csharp
105
WeakReferenceMessenger.Default.Send(new ThemeChangedMessage(AppTheme.Dark));
106
107
// Empty payloads use the parameterless overload:
108
WeakReferenceMessenger.Default.Send<RefreshRequestedMessage>();
109
```
110
111
---
112
113
## Channels (tokens)
114
115
Scope messages to a sub-system or window with a token (any equatable
116
value — `int`, `string`, `Guid`):
117
118
```csharp
119
const int LeftPaneChannel = 1;
120
121
WeakReferenceMessenger.Default.Register<MyViewModel, RefreshRequestedMessage, int>(
122
this, LeftPaneChannel,
123
static (r, _) => r.RefreshLeft());
124
125
WeakReferenceMessenger.Default.Send(new RefreshRequestedMessage(), LeftPaneChannel);
126
```
127
128
Messages sent without a token use the default shared channel — they are
129
**not** delivered to channel-scoped recipients.
130
131
---
132
133
## Request / reply
134
135
For ask-style scenarios where a recipient provides a value back to the
136
sender, use the `RequestMessage<T>` family.
137
138
### Sync request
139
140
```csharp
141
public sealed class CurrentUserRequest : RequestMessage<User> { }
142
143
WeakReferenceMessenger.Default.Register<UserService, CurrentUserRequest>(
144
this,
145
static (r, m) => m.Reply(r.CurrentUser));
146
147
User user = WeakReferenceMessenger.Default.Send<CurrentUserRequest>();
148
```
149
150
The implicit conversion from `CurrentUserRequest` to `User` throws if no
151
recipient called `Reply`. Capture the message to check first:
152
153
```csharp
154
var request = WeakReferenceMessenger.Default.Send<CurrentUserRequest>();
155
if (request.HasReceivedResponse)
156
User user = request.Response;
157
```
158
159
### Async request
160
161
```csharp
162
public sealed class CurrentUserRequest : AsyncRequestMessage<User> { }
163
164
WeakReferenceMessenger.Default.Register<UserService, CurrentUserRequest>(
165
this,
166
static (r, m) => m.Reply(r.GetCurrentUserAsync()));
167
168
User user = await WeakReferenceMessenger.Default.Send<CurrentUserRequest>();
169
```
170
171
### Collection requests (fan-in)
172
173
`CollectionRequestMessage<T>` and `AsyncCollectionRequestMessage<T>` collect
174
a `Reply` from every responding recipient:
175
176
```csharp
177
public sealed class OpenDocumentsRequest : CollectionRequestMessage<Document> { }
178
179
var docs = WeakReferenceMessenger.Default.Send<OpenDocumentsRequest>();
180
foreach (Document doc in docs) { /* ... */ }
181
```
182
183
---
184
185
## Lifecycle
186
187
Even with `WeakReferenceMessenger`, unregister explicitly when a recipient
188
is being torn down — it trims dead entries and improves performance:
189
190
```csharp
191
WeakReferenceMessenger.Default.Unregister<ThemeChangedMessage>(this);
192
WeakReferenceMessenger.Default.Unregister<ThemeChangedMessage, int>(this, LeftPaneChannel);
193
WeakReferenceMessenger.Default.UnregisterAll(this);
194
```
195
196
`ObservableRecipient.OnDeactivated()` does this automatically when
197
`IsActive` flips to `false`. Set it from your activation hook:
198
199
```csharp
200
protected override void OnNavigatedTo(NavigationEventArgs e)
201
{
202
base.OnNavigatedTo(e);
203
ViewModel.IsActive = true;
204
}
205
206
protected override void OnNavigatedFrom(NavigationEventArgs e)
207
{
208
ViewModel.IsActive = false;
209
base.OnNavigatedFrom(e);
210
}
211
```
212
213
---
214
215
## Common pitfalls
216
217
1. **Capturing `this` in the lambda.** `(r, m) => OnX(m)` implicitly
218
captures `this`; allocates a closure and confuses lifetime. Always use
219
`(r, m) => r.OnX(m)` with `static`.
220
2. **Strong-ref recipients without `Unregister`.** With
221
`StrongReferenceMessenger`, recipients (and their entire object graph)
222
stay pinned forever. Either inherit from `ObservableRecipient`
223
(auto-unregisters in `OnDeactivated`) or call `UnregisterAll(this)`.
224
3. **Inherited message types.** A handler registered for `BaseMessage` is
225
**not** invoked for `DerivedMessage : BaseMessage`. Register each
226
concrete type.
227
4. **Wrong messenger instance.** Sending via `WeakReferenceMessenger.Default`
228
and registering via an injected per-window messenger means the message
229
never arrives. Use the same `IMessenger` everywhere (typically inject
230
it via `ObservableRecipient(messenger)`).
231
5. **`OnActivated` never runs.** `ObservableRecipient` only registers
232
`IRecipient<T>` handlers when `IsActive` flips from `false` to `true`.
233
6. **Cross-thread updates.** The messenger is thread-agnostic. If a
234
handler updates UI, marshal manually
235
(`DispatcherQueue.TryEnqueue` / `Dispatcher.BeginInvoke`).
236
237
---
238
239
## Multiple messengers (per-window scoping)
240
241
```csharp
242
services.AddSingleton<IMessenger>(WeakReferenceMessenger.Default); // app-wide
243
services.AddScoped<WindowScopedMessenger>(); // per-window
244
```
245
246
Inject the appropriate `IMessenger` into the ViewModel constructor:
247
248
```csharp
249
public sealed partial class WindowViewModel(IMessenger messenger)
250
: ObservableRecipient(messenger) { }
251
```
252
253
This isolates broadcasts to a single window — useful for multi-window
254
desktop apps (WinUI 3, WPF, MAUI desktop, Avalonia).
255
256
---
257
258
## References
259
260
| Topic | File |
261
|-------|------|
262
| Full deep dive (more channel/lifecycle examples, diagnostics) | [`references/messenger-patterns.md`](references/messenger-patterns.md) |
263
264
External:
265
266
- Messenger docs: <https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/messenger>
267
- `WeakReferenceMessenger` API: <https://learn.microsoft.com/en-us/dotnet/api/communitytoolkit.mvvm.messaging.weakreferencemessenger>
268
- Source: <https://github.com/CommunityToolkit/dotnet>
269

© 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…