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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With