Search code examples
messagingmaui

Use .NET Maui WeakReferenceManager to send message from ViewModel to View?


.NET MAUI now has a WeakReferenceManager which works beautifully when sending messages from one ViewModel to another ViewModel. Is it possible to use this when sending a message from a ViewModel to a View?


Solution

  • Thank you to the commenters. The full answer is:

    1. Create a class that will serve as the message. Call it anything you like.
    public class MyMessage {}
    
    1. In the code-behind page register to receive that message. I opted to combine that with a lambda that does the actual work when the message is received:
    WeakReferenceMessenger.Default.Register<MyMessage>(this, async (m,e) =>
    {
        // do the work here
    });
    
    1. In the XAML add a command (e.g, ShowMyMessageCommand)

    2. In the ViewModel send the message in the RelayCommand:

    [RelayCommand]
    private void ShowMyMessage()
    {
        WeakReferenceMessenger.Default.Send(new MyMessage());
    }