How do I share data between multiple ViewModels ?
For example there is a class named Project in application .
public class Project : ModelBase
{
private string _projectName;
public string ProjectName
{
get { return _projectName; }
set
{
_projectName = value;
RaisePropertyChanged(() => ProjectName);
}
}
}
In multiple ViewModels application should access ActiveProject.
What's the best way to share Project between ViewModels ?
- Mediator Pattern ? (Messaging)
- Static object
- Singleton pattern (If yes how?)
I've used Messaging before but it needs much codding . For all ViewModels I've to create ActiveProject property and also have to register a messenger to update that.
I use MVVM Light framework.
Any code example would be appreciated.
ActiveProject
created somewhere by one of the view models? If so, messaging would probably be the best (and it's not that verbose). Other option is to inject anActiveProject
to every view model that needs it while setting theActiveProject
lifetime to singleton in the IoC container of choice - third option you've suggested... But so far it's mostly guessing on my part. – Patryk ĆwiekApp
class as a static property? – Federico Berasateguicontainer.RegisterSingle<Project>(() => new Project());
and then just request aProject activeProject
in the constructor. Other IoC containers also support named injection, so you can use that too. – Patryk Ćwiek