I have tried to use MVVM Light messaging to communicate between different ViewModels, but with time it gets quite messy and hard to understand from where and where to all the messages are flying so I wanted to ask about other solution how to communicate between ViewModels using Interfaces. The provided code works well, but I am not sure if Interfaces are mended to be used this way.. So here I have defined interface and class that implements it:
public interface ISelectProject
{
event EventHandler<SelectedProjectEventArgs> MessageReceived;
void ProjectSelected(...);
}
public class SelectProject : ISelectProject
{
public event EventHandler<SelectedProjectEventArgs> MessageReceived;
public void ProjectSelected(..)
{
MessageReceived?.Invoke(this,new SelectedProjectEventArgs(...));
}
}
Afterward, I inject SelectProject class into these tree ViewModels using constructor injection(code not shown here). Then in ViewModelA I invoke MessageReceived event and all the other ViewModels subscribe to the event.
public class ViewModelA : ViewModelBase
{
public ViewModelA(ISelectProject selectProject)
{
_selectProject = selectProject;
_selectProject.ProjectSelected;
}
}
public class ViewModelB : ViewModelBase
{
public ViewModelB(ISelectProject selectProject)
{
_selectProject = selectProject;
_selectProject.MessageReceived += (s, data) =>
{
...
};
}
}
public class ViewModelC : ViewModelBase
{
public ViewModelC(ISelectProject selectProject)
{
_selectProject = selectProject;
_selectProject.MessageReceived += (s, data) =>
{
...
};
}
}
My questions are:
1) Does this somehow violate MVVM practice?
2) Is it considered a good practice to communicate between ViewModels like this?
3) Does this solution introduce any risks, for example, memory leaks, etc?
Thank you!