跨 ViewModel 共享状态/更改 [英] Sharing state/changes across ViewModels
问题描述
我有一个应用程序,它有一个任务选项卡和一个项目选项卡.我决定为每个选项卡、TasksViewModel 和 ProjectsViewModel 创建一个单独的 ViewModel.
I have an App which has a Tasks tab and a Projects tab. I decided to make a separate ViewModel for each of the tabs, TasksViewModel and ProjectsViewModel.
任务"选项卡有一个新的任务区域和一个关联的项目下拉菜单,项目"选项卡(显然)有一个项目列表.
The Tasks tab has a new task area with an associated project pulldown and the Projects tab (obviously) has a list of projects.
我希望任务"选项卡上的下拉菜单与项目"选项卡列表共享相同的集合,以便我在项目"选项卡上添加或删除项目时,任务"选项卡上的列表都是最新的自动地.这适用于单个 ViewModel,但它开始变得非常不守规矩.
What I'd like is for the pulldown on the Tasks tab to share the same collection as the Projects tab list so that any time I add or remove a project on the Projects tab the list on the Tasks tab is up to date automatically. This worked well with a single ViewModel but it was beginning to become quite unruly.
我不应该分成两个 ViewModel 吗?有没有像这样共享数据的通用方法?也许将相同的 ObservableCollection
传递到每个 ViewModel 中?也许某种类型的通知沿着 ICollectionChanged
行返回到 TasksViewModel.
Should I not have split into two ViewModels? Is there a common method of sharing data like this? Perhaps pass the same ObservableCollection<Project>
into each of the ViewModels? Perhaps some type of notification back to the TasksViewModel along the lines of ICollectionChanged
.
感谢任何见解/意见!
推荐答案
这里最简单的解决方案通常是使用某种形式的 Messaging Service 在两个 ViewModel 之间传递信息.
The easiest solution here is often to use some form of Messaging Service to pass information between the two ViewModels.
例如,MVVM Light Toolkit 提供了一个 IMessenger 界面,适用于这种情况.
For example, the MVVM Light Toolkit provides an IMessenger interface for situations like this.
在这种情况下,使用好的 IoC 或 DI 工具集也有帮助.这将允许您将项目集合动态注入到您的两个视图模型中,从而允许在两个视图中使用共享集合.
Using a good IoC or DI toolset can help in this situation, as well. That would let you inject the project collection dynamically into both of your ViewModels, allowing a shared collection to be used in both Views.
这篇关于跨 ViewModel 共享状态/更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!