Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a viewmodel from another viewmodel

I have two ViewModels one is attached to a main window and the other is attached to child window that is opened by clicking on a button on the main window. The child window contains a list of items and I want to select an item and display it in the main window by updating the main window viewmodel. What is the best way to accomplish this. Thanks!

like image 975
codeBlue Avatar asked Apr 20 '11 15:04

codeBlue


People also ask

Can a ViewModel have multiple models?

ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method. In the above example, we have the required View model with two properties.

Can ViewModel have reference view?

Caution: A ViewModel must never reference a view, Lifecycle , or any class that may hold a reference to the activity context.

Can ViewModel have logic?

ViewModel: ViewModel is the middle layer between the view and model. ViewModel contains the business logic, which manipulates the row data to show in the view. Any kind of function and methods should be in the view model. The iNotifyPropertyChanged interface is used in the ViewModel to achieve two-way binding.

Should a ViewModel have a constructor?

At present, this means that every ViewModel must have a public constructor which has either no parameters or which has only string parameters.


1 Answers

There are any number of ways to do this.

  • Pass a reference to the main/parent view model into the child and have the child call the main view model.

  • Have the child view model fire an event that the parent subscribes to.

  • Use a messenger/mediator to communicate between the two. The parent subscribes, the child posts the message. This provides loose coupling.

  • Set the main view model up as a global service. Register it somehow. Have the child look up the service (requiring global services is a pretty common problem) and then call something on the global/common interface.

From my experience, the simplest method would be #2. Define an event on the child view model. The parent will have to look up the child (I don't know if it contains it or how your view models are constructed) and subscribe to the event.

like image 72
Josh G Avatar answered Sep 29 '22 03:09

Josh G