How to access ViewModel for viewing

Say I have a simple view that displays some text. The text comes from the View ViewModel using the string property associated with the data. I would like to be able to set the ViewModel line in several places in the application.

What is the best practice for getting an instance of ViewModel at different points in my application?

I could make SingleMonel ViewModel, but I didn’t like it.

Any suggestions?

+4
source share
2 answers

I think there are different concepts for this. Each has its pros and cons ....

1.) If you do not have parameters in the constructor of the view model, you can use the DataContext property of the control, view, page to bind the view model. He expands the instance to view ...

2.) If you have complex or linked view models with constructor inserts ... The best way would be a ViewModel locator template based on the Locator service template.

http://johnpapa.net/simple-viewmodel-locator-for-mvvm-the-patients-have-left-the-asylum http://blog.roboblob.com/tag/viewmodellocator/

3.) First you need to think about the first look or view of the model and, perhaps, something like a marriage to the view model ... http://wildermuth.com/2009/5/22/Which_came_first_the_View_or_the_Model

NTN

+1
source

I think you are looking for something like Messenger where your view model can register for messages to change the property of the string, and other components can send a message through the messenger.

Another approach is the PRISM event aggregator, where you can subscribe to events when your row property needs to be changed.

EDIT: Another but bad way is to provide an instance of your view model for all other locations. but then you no longer have free communication.

0
source

Source: https://habr.com/ru/post/1399380/


All Articles