Reputation: 2905
Let's say I have a simple View that displays a bit of text. The text comes from the View's ViewModel via a string property that is data bound. I would like to be able to set the ViewModel's string by multiple locations in the application.
What is the best practise for getting the instance of the ViewModel at the various points in my application?
I could make the ViewModel singleton but this didn't feel right.
Any suggestions?
Upvotes: 4
Views: 2671
Reputation: 22445
i think you looking for something like a Messenger where your viewmodel can register for messages to change your string property and other components can send a message via messenger.
another approach is the PRISM event aggregator where you can subscribe to events when your string property should be changed.
EDIT: an other but bad way would be to give an instance of your viewmodel to all other locations. but then you have no more loose coupling.
Upvotes: 0
Reputation: 6882
I think there are different concepts for that. Each has it's pros and cons....
1.) If you have have not parameters in the constructor of the view model you could use the DataContext Property of the Control, View, Page to bind the view model. It spin's up a instance per View...
2.) If you have complex or composed view models with constructor injections ... The best way would be the ViewModel Locator Pattern based on a Service Locator Pattern.
http://johnpapa.net/simple-viewmodel-locator-for-mvvm-the-patients-have-left-the-asylum http://blog.roboblob.com/tag/viewmodellocator/
3.) you have to think about view first or view model first and maybe about something like a view model marriage... http://wildermuth.com/2009/5/22/Which_came_first_the_View_or_the_Model
HTH
Upvotes: 1