Author : Admin
Last Modified : 26-Aug-2022
Complexity : Intermediate
How to communicate or pass data between two viewmodels or classes with the help of event?
In WPF, Sometimes we need to communicate between the view models. But if we access the object of one ViewModel in another ViewModel then we violate the rule of loose coupling. So as a solution we can inject the dependency via the interface or use an event to pass the data.
Here in this article, we will see how to communicate between two view models.
Create the Util class where we define the events.
namespace ViewmodelCommunication
{
public delegate void SendData(string data);
public class GurukultreeUtil
{
private static GurukultreeUtil instance;
public static GurukultreeUtil Instance
{
get
{
if (instance == null)
{
instance = new GurukultreeUtil();
}
return instance;
}
}
//Define the event
public event SendData SendData;
public void RaiseSendData(string data)
{
SendData?.Invoke(data);
}
}
}
Define FirstViewModel, FirstViewModel will pass the data to SecondViewModel.
namespace ViewmodelCommunication
{
public class FirstViewModel : BaseViewModel
{
public FirstViewModel()
{
PassDataToSecondViewModel();
}
public void PassDataToSecondViewModel()
{
GurukultreeUtil.Instance.RaisedSendData("Gurukultreess");
}
}
}
Define SecondViewModel, In SecondViewModel we need to subscribe to the event when the event is invoked via FirstViewModel the method registered with the event will be called.
namespace ViewmodelCommunication
{
public class SecondViewModel : BaseViewModel
{
public SecondViewModel()
{
GurukultreeUtil.Instance.SendData += Instance_SendData;
}
private void Instance_SendData(string data)
{
var recivedData = data;
}
}
}
In this way, we can communicate between two view models(classes).