我应该如何将集合从一个视图的 ViewModel 传递到另一个视图?
任何人都可以在以下场景中提出解决方案:
我有一个 MVVM 应用程序,我需要在主窗口中显示模式窗口,以向 viewModel 类中的 Collection 添加一些值。做到这一点的最佳方法是什么?我是说。我需要更改 viewModel 中的一些集合,我的 MainWindow 引用了 viewMode。
viewModel = new ExamViewModel();
this.DataContext = viewModel;
将 viewmodel 也暴露给子窗口是否足够好?或者有“正确”的方法来做到这一点。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,模式窗口只会知道有问题的对象,允许用户填写新对象(也可能编辑现有对象)。然后它将填充的对象传递回父级,父级负责更新集合。
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.
正如 @Marcelo 建议的那样,打开新子窗口的代码应该与 ViewModel 中的一些委托一起传递。该委托将创建一个子 ViewModel(例如
ChildVM
),并使用其自己的集合(ParentVM.ParentCollection
)填充其属性之一(例如ChildCollection
) )。然后,您的子窗口将绑定到新填充的集合(ChildVM.ChildCollection)属性,并在执行“确定”/“保存”类型的确认操作后,关闭的子窗口应通知/委托回父视图模型以“合并” “更改回其旧集合...像这样...
这样
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 (sayChildCollection
) with its own collection (ParentVM.ParentCollection
).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...
This way