Reputation: 43
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
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
Upvotes: 0
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