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!
1) Does this somehow violate MVVM pratice?
No. ISelectedProject
is basically a shared service. A shared service is a class that provides functionality to several components in a decoupled way. Please refer to this link for more information and an example.
2) Is it considered a good practice to communicate between viewModels like this?
Yes, if you want to keep them decoupled from each other.
3) Does this solution introduces any risks, for example memory leaks, etc.
Using a shared service doesn't introduce any memory leaks by itself. But if your shared service exposes an event and a view model subcribes to this one without unsubscribing from it, the service will keep the view model alive.