user964124
user964124

Reputation: 43

How should I pass collections from one view's ViewModel to another View?

can anyone please advise a solution in following scenario :

I have an MVVM application in which I need to show modal window from Main window to add some value to the Collection that is in viewModel class. What will be the best approach to do this. I mean. I need to change some collection in viewModel , My MainWindow have reference to viewMode.

 viewModel = new ExamViewModel();
 this.DataContext = viewModel;

Is it good enough to expose viewmodel also to child window ? Or there is "right" way to do this.

Upvotes: 0

Views: 388

Answers (2)

Vinit Sankhe
Vinit Sankhe

Reputation: 19885

As @Marcelo suggested, your code that opens the new child window should be passed on with some delegate from your ViewModel. This delegate will create a child ViewModel (say ChildVM) and populate one of its properties (say ChildCollection) with its own collection (ParentVM.ParentCollection).

  var childVM = new ChildVM();
  childVM.ChildCollection = parentVM.ParentCollection.ToList();
  return childVM;

Then your child window will be bound to that newly populated collection (ChildVM.ChildCollection) property and after it performs "OK" / "SAVE" kind of affirmation actions, the closed child window should notify / delegate back to the parent viewmodel to "incorporate" changes back to its old collection... like so...

   parentVM.ParentCollection.Clear(); 
   parentVM.ParentCollection.AddRange(ChildVM.ChildCollection);

This way

  1. Changes are done on seperate lists. Data integrity is maintained.
  2. ONLY a legitimate action (OK / SAVE) merges the changes.
  3. Child viewmodel is easily plugged off the UI and and disposed off the memory due to disconnected data and the unloaded child view.

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

Normally, the modal window will only know about the object in question, allowing the user to fill in a new object (and possibly also edit an existing object). It will then pass the filled-in object back to the parent, which is responsible for updating the collection.

Upvotes: 1

Related Questions