Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicating between ViewModels with Events

Tags:

c#

mvvm

wpf

I am trying to communicate events from my child ViewModel back to the parent. The child viewmodel's view is a separate window that I believe I cannot pass constructor arguments to. A button on this view needs to trigger a method on the parent ViewModel.

Child ViewModel:

public ConnectViewModel(ConnectEvents connectEvents)
{
    ConnectEvents = connectEvents;
}

Parent ViewModel

public MainWindowViewModel()
{
    ConnectEvents connectEvents = new ConnectEvents();
    ConnectViewModel = new ConnectViewModel(connectEvents);
    connectEvents.ThrowEvent += ConnectToServer;
}

How can I communicate between these two? Is there a better system, or how can I allow the parents to subscribe to the child?

like image 378
user547794 Avatar asked Dec 03 '22 21:12

user547794


2 Answers

You have a lot of choices. You can use custom event, you can use delegate directly, you can subscribe in your parent ViewModel to the PropertyChanged or CollectionChanged event, using either ordinary subscription, or Weak Event Pattern.

I prefer the last one because there is no need to unsubscribe from.

like image 138
stukselbax Avatar answered Dec 05 '22 11:12

stukselbax


You can make your own EventAggregator

public static class DumbAggregator
{
  public static void BroadCast(string message)
  {
   if (OnMessageTransmitted != null)
       OnMessageTransmitted(message);
  }

 public static Action<string> OnMessageTransmitted;
}

Usage:

  public class MySender
  {
    public void SendMessage()
    {
      DumbAggregator.BroadCast("Hello There!");
    }
  }

public class MySubscriber
{
  public MySubscriber()
  {
   DumbAggregator.OnMessageTransmitted += OnMessageReceived;
  }

 private void OnMessageReceived(string message)
 {
  MessageBox.Show("I Received a Message! - " + message);
 }
}

and with the help of this you can communicate with your view models

like image 27
Mohd Ahmed Avatar answered Dec 05 '22 11:12

Mohd Ahmed