开发者

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

开发者 https://www.devze.com 2023-04-08 03:45 出处:网络
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 c

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.


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.


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消