Index of every page on this site: llms.txt
All skills
github avatar

/mvvm-toolkit-messenger

@f10fdb8 official
by githubgithub/awesome-copilot42k stars
5,426
Run it yourself

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.

Use this Skill: https://skilld.dev/gh/github/awesome-copilot/mvvm-toolkit-messenger

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesmessenger-patterns.md

≈1.8k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Messenger patterns

CommunityToolkit.Mvvm.Messaging provides decoupled pub/sub between ViewModels (or any objects) without forcing a shared reference graph.

Choosing an implementation

Type When to use
WeakReferenceMessenger.Default Default. Recipients held weakly — eligible for GC even if still registered. Internal trimming runs during full GCs. No manual Cleanup() required.
StrongReferenceMessenger.Default Use when profiling shows the messenger is hot and allocation matters. Recipients are pinned until you Unregister. Forgetting to unregister leaks them.
Custom IMessenger instance Per-window/per-scope messengers (e.g., one per app window). Construct directly and inject through DI.

ObservableRecipient's parameterless constructor uses WeakReferenceMessenger.Default. Pass a different IMessenger to its constructor to override.


Defining messages

The toolkit ships a few base classes you can inherit from, but any class works.

Plain payload

public sealed record ThemeChangedMessage(AppTheme NewTheme);

ValueChangedMessage<T>

using CommunityToolkit.Mvvm.Messaging.Messages;

public sealed class LoggedInUserChangedMessage(User user)
    : ValueChangedMessage<User>(user);

Access the payload via .Value.

Empty signal

public sealed record RefreshRequestedMessage;

Useful for "reload now" or "save now" broadcasts where there is no payload.


Registering recipients

Lambda style (recommended)

WeakReferenceMessenger.Default.Register<MyViewModel, ThemeChangedMessage>(
    this,
    static (recipient, message) => recipient.OnThemeChanged(message.NewTheme));

The static modifier ensures the lambda doesn't capture this (or any local variable), keeping it allocation-free and preventing accidental strong references back to the recipient through closure capture.

IRecipient<TMessage> interface style

public sealed class MyViewModel : ObservableRecipient,
    IRecipient<ThemeChangedMessage>,
    IRecipient<RefreshRequestedMessage>
{
    public void Receive(ThemeChangedMessage message) { /* ... */ }
    public void Receive(RefreshRequestedMessage message) { /* ... */ }
}

ObservableRecipient.OnActivated() calls Messenger.RegisterAll(this), which subscribes every IRecipient<T> interface implemented by the type.

If you're not using ObservableRecipient, register manually:

WeakReferenceMessenger.Default.RegisterAll(this);

Sending messages

WeakReferenceMessenger.Default.Send(new ThemeChangedMessage(AppTheme.Dark));

// Empty payloads can use the parameterless overload:
WeakReferenceMessenger.Default.Send<RefreshRequestedMessage>();

Channels (tokens)

Send/receive over a named channel to scope messages to a sub-system. The token is any equatable value (commonly int, string, or Guid).

const int LeftPaneChannel = 1;
const int RightPaneChannel = 2;

WeakReferenceMessenger.Default.Register<MyViewModel, RefreshRequestedMessage, int>(
    this, LeftPaneChannel,
    static (r, _) => r.RefreshLeft());

WeakReferenceMessenger.Default.Send(new RefreshRequestedMessage(), LeftPaneChannel);

Messages sent without a token use the default shared channel and are not delivered to channel-scoped recipients.


Request / reply

For ask-style scenarios where a recipient should provide a value back to the sender, use the RequestMessage<T> family.

Sync request

public sealed class CurrentUserRequest : RequestMessage<User> { }

// Recipient
WeakReferenceMessenger.Default.Register<UserService, CurrentUserRequest>(
    this,
    static (r, m) => m.Reply(r.CurrentUser));

// Caller
User user = WeakReferenceMessenger.Default.Send<CurrentUserRequest>();

The implicit conversion from CurrentUserRequest to User throws if no recipient called Reply. To check first, capture the message:

var request = WeakReferenceMessenger.Default.Send<CurrentUserRequest>();
if (request.HasReceivedResponse)
{
    User user = request.Response;
}

Async request

public sealed class CurrentUserRequest : AsyncRequestMessage<User> { }

WeakReferenceMessenger.Default.Register<UserService, CurrentUserRequest>(
    this,
    static (r, m) => m.Reply(r.GetCurrentUserAsync()));

User user = await WeakReferenceMessenger.Default.Send<CurrentUserRequest>();

Collection requests (fan-in)

CollectionRequestMessage<T> and AsyncCollectionRequestMessage<T> collect a Reply from every recipient that handles the message:

public sealed class OpenDocumentsRequest : CollectionRequestMessage<Document> { }

var responses = WeakReferenceMessenger.Default.Send<OpenDocumentsRequest>();
foreach (Document doc in responses) { /* ... */ }

Unregistering

Always unregister when a recipient's lifetime ends. With WeakReferenceMessenger, this is for performance (trimming dead entries); with StrongReferenceMessenger, it's required to avoid leaks.

WeakReferenceMessenger.Default.Unregister<ThemeChangedMessage>(this);
WeakReferenceMessenger.Default.Unregister<ThemeChangedMessage, int>(this, LeftPaneChannel);
WeakReferenceMessenger.Default.UnregisterAll(this);

ObservableRecipient.OnDeactivated() unregisters everything for you when IsActive flips to false — set IsActive = true in your activation flow (e.g., page OnNavigatedTo) and IsActive = false on tear-down.


Lifetime pitfalls

  1. Closure-captured this. Avoid (r, m) => OnX(m) lambdas that implicitly capture the enclosing this. Use (r, m) => r.OnX(m) so the recipient is passed in instead.
  2. Long-lived strong-ref recipients. With StrongReferenceMessenger, forgetting UnregisterAll keeps the recipient (and its entire object graph) alive forever.
  3. Inherited message types. A handler registered for BaseMessage is not invoked for DerivedMessage : BaseMessage. Register each concrete type you want to handle.
  4. Multiple ObservableRecipient activations. Setting IsActive = true twice without an intermediate deactivation throws — guard the toggle.
  5. UI-thread marshalling. The messenger is thread-agnostic. If a handler updates UI, marshal manually (DispatcherQueue.TryEnqueue / Dispatcher.BeginInvoke).

Multiple messengers

A common architecture is one messenger per window or per scope:

services.AddSingleton<IMessenger>(WeakReferenceMessenger.Default);  // app-wide
services.AddScoped<WindowScopedMessenger>();                        // per-window

Inject the appropriate IMessenger into the ViewModel constructor:

public sealed partial class WindowViewModel(IMessenger messenger)
    : ObservableRecipient(messenger) { /* ... */ }

This isolates broadcasts to a single window — useful for multi-window desktop apps (WinUI 3, WPF, MAUI desktop, Avalonia).

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts11d3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    This skill provides instructional documentation and C# code snippets for using the CommunityToolkit.Mvvm Messenger library. It contains no executable code, malicious patterns, or security risks.

  • Socket11d

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at f10fdb8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 days ago.

Activeupdated 7 months ago
  • mvvm
  • messaging
  • pub-sub
  • viewmodel
  • wpf
  • winui
  • maui
  • csharp
  • weak-reference
  • channels

README badge

README badge for github/awesome-copilot/mvvm-toolkit-messenger

Pub/sub messaging for ViewModels in WPF, WinUI 3, .NET MAUI, Uno, and Avalonia using CommunityToolkit.Mvvm's WeakReferenceMessenger and StrongReferenceMessenger. Handles decoupled communication, request/reply patterns, channel scoping, and lifecycle management through ObservableRecipient activation.

Generated from the current SKILL.md.

Should I use WeakReferenceMessenger or StrongReferenceMessenger?
Default to WeakReferenceMessenger.Default. Use StrongReferenceMessenger only if profiling shows the messenger is a hotspot and allocation matters, but you must then manually call Unregister to avoid pinning recipients forever.
Do I need to unregister handlers when using WeakReferenceMessenger?
Yes. Even though recipients are held weakly, unregistering explicitly when they're torn down trims dead entries and improves performance. ObservableRecipient does this automatically in OnDeactivated when IsActive flips to false.
Why doesn't my handler fire when I inherit from a message base class?
A handler registered for a base message type is not invoked for derived message types. Register each concrete message type separately.
Can I scope messages to a subset of recipients?
Yes, use channels (tokens). Pass an equatable value like an int or string to both Register and Send overloads to scope messages to specific sub-systems or windows. Messages sent without a token use the default shared channel.
How do I implement request/reply messaging?
Use RequestMessage<T> for sync replies, AsyncRequestMessage<T> for async, or CollectionRequestMessage<T> to collect replies from multiple recipients. Recipients call m.Reply() and senders check HasReceivedResponse or await the send call.

Generated from the current SKILL.md. These answers refresh after source changes.