using System.Collections.Generic;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Input;
public class NotificationMessage
public string Content { get; }
public NotificationMessage(string content) => Content = content;
public class GetUserRequest : RequestMessage<User> { }
public string Name { get; set; }
public class UserViewModel : ObservableRecipient, IRecipient<NotificationMessage>, IRecipient<GetUserRequest>
public RelayCommand DisplayUserCommand { get; }
DisplayUserCommand = new RelayCommand(ExecuteDisplayUser);
public void Receive(NotificationMessage message)
Console.WriteLine($"Notification: {message.Content}");
public void Receive(GetUserRequest request)
request.Reply(new User { Name = "John Doe" });
private void ExecuteDisplayUser()
Console.WriteLine("DisplayUserCommand executed!");
public class UserRecipient
private readonly IMessenger _messenger;
public UserRecipient(IMessenger messenger)
_messenger.Register(this, new MessageHandler<UserRecipient, NotificationMessage>((recipient, message) =>
recipient.HandleNotification(message);
private void HandleNotification(NotificationMessage message)
Console.WriteLine($"Notification received: {message.Content}");
static void Main(string[] args)
var viewModel = new UserViewModel();
var request = new GetUserRequest();
WeakReferenceMessenger.Default.Send(request);
var user = request.Response;
Console.WriteLine($"User: {user.Name}");
IMessenger messenger = WeakReferenceMessenger.Default;
var userRecipient = new UserRecipient(messenger);
messenger.Send(new NotificationMessage("You have a new message!"));
Console.WriteLine("Testing RelayCommand...");
viewModel.DisplayUserCommand.Execute(null);