Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVMCross - Bind the same ViewModel to 2 different Views

Tags:

mvvm

mvvmcross

Basically my scenario is the following: I have 1 View bound to a ViewModel, with a List of items(the items' class is a class in my Model). Every time an item is selected from the list in this 'List View', its fields are edited in another, 'Details View'. This is identical to the Customer Management sample scenario, where a customer is selected from the List (in a 'List View') and the the Customer's details can be changed in a 'Details View'. The added quirk in my scenario, is that I want the changes done to the item in the Details View, to be reflected back in the List View. The changes are saved in DB from the Details View.

Also, depending on the changes done in the Details View, the item can be removed from list in the first View. Note that this is not deleting the record from the DB, because the list in the List View is just a filtered list of the items in the DB. I figured out two possible ways that I can do this:

  1. By binding the 2 Views to the same View Model

EDIT: How do I call the second view? Will the second view actually use the same instance of the shared ViewModel?

-or- 2. By passing the item selected in the List View by reference to the Details View. Therefore in this case, I'm maintaining the 1-View-to-1-ViewModel mapping.

My questions are:

  • how can I implement scenario 1,
  • in 2, does the Init() method(used in conjunction with the ShowViewModel() method) support passing parameters by reference?

I would be grateful, if you could include code snippets/examples in your answers.

Thanks a lot in advance,

like image 863
Pap Avatar asked Jan 26 '26 02:01

Pap


1 Answers

binding 2 Views to the same View Model

You are free to set the ViewModel property on any View manually if you wish to. Simply set ViewModel = foo; before the call to base.OnCreate(), base.OnNavigatedTo() or base.ViewDidLoad()

in 2, does the Init() method(used in conjunction with the ShowViewModel() method) support passing parameters by reference?

MvvmCross does not support passing objects between ViewModels. On Windows Phone navigations are performed by url parameters. On Android, navigations are performed by Intents - these underlying mechanisms simply do not let you pass actual object references.


In general I handle this situation using messaging from the data store to the ViewModel

I would be grateful, if you could include code snippets/examples in your answers.

You can see how I typically do this in N=12 to N=15 in http://mvvmcross.wordpress.com/

like image 92
Stuart Avatar answered Jan 28 '26 19:01

Stuart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!