2

.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?

3
  • Yes. I use it often like that. In your Page constructor, call WeakReferenceManager.Default.Regirster<MyMessage>(this, ... and define your method. Commented Dec 29, 2022 at 11:29
  • 2
    Sure, it is possible. It wouldn't violate the MVVM. There is also another option since View and ViewModel linked. You can create an EventHandler inside your Viewmodel, trigger the EventHandler from your ViewModel and handle the Event from your View. I go for the second option if the message interests only the View. Commented Dec 29, 2022 at 12:07
  • The penny finally dropped for me based on your comments, thanks. I'm going to fill in and accept the answer. Commented Dec 29, 2022 at 21:26

1 Answer 1

4

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());
}
Sign up to request clarification or add additional context in comments.

2 Comments

@ewerspej saved my message by reformatting it properly. I'm not sure why I had so much trouble with getting the code to format correctly (I used the {} menu choice), but I do appreciate his fixing it up. Thanks!
You can go into the editor or history to see what I've changed. Maybe that helps with future posts. Anyway, you're welcome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.