.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?
-
Yes. I use it often like that. In your Page constructor, call WeakReferenceManager.Default.Regirster<MyMessage>(this, ... and define your method.H.A.H.– H.A.H.2022-12-29 11:29:01 +00:00Commented Dec 29, 2022 at 11:29
-
2Sure, 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.tataelm– tataelm2022-12-29 12:07:13 +00:00Commented 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.Jesse Liberty– Jesse Liberty2022-12-29 21:26:57 +00:00Commented Dec 29, 2022 at 21:26
Add a comment
|
1 Answer
Thank you to the commenters. The full answer is:
- Create a class that will serve as the message. Call it anything you like.
public class MyMessage {}
- 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
});
In the XAML add a command (e.g,
ShowMyMessageCommand)In the ViewModel send the message in the
RelayCommand:
[RelayCommand]
private void ShowMyMessage()
{
WeakReferenceMessenger.Default.Send(new MyMessage());
}
2 Comments
Jesse Liberty
@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!
Julian
You can go into the editor or history to see what I've changed. Maybe that helps with future posts. Anyway, you're welcome.