FPGA
FPGA

Reputation: 3855

Updating another ViewModel on PropertyChanged of another ViewModel

Both ViewModels know nothing about each other, but i need to send the new value that have changed in one viewmodel to a method in the other view model, what are my options?

could you please list all possibilities and what would be the best way?

Upvotes: 2

Views: 1890

Answers (1)

Fede
Fede

Reputation: 44038

Taken from this answer:

If you want loosely-coupled communication you need an EventAggregator:

//Simplest 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);
   }
}

Notice however, that EventAggregators included in MVVM frameworks such as Prism are much more complex and include a whole lot of functionality. This is just a simple example.

Upvotes: 3

Related Questions