如何将 MVVM 模型中的列表转换为视图模型中的 ObservableCollections?
我正在 WPF 中编写一个示例应用程序,并且希望该模型能够在 WinForms 应用程序中轻松重用,因此我希望将 WPF 特定的内容(例如 INotifyChanged 和 DependencyObjects)保留在其中。
如果一个模型类有一个其他模型类的列表,我如何在视图模型中实现相应的 ObserveableCollection 以便我可以保持我的绑定最新?
一个用例是,如果我有一个 Boss 模型对象,其中包含 Employee 列表。我创建了一个 Boss 对象,但异步加载了员工列表,我如何知道何时检索并填充了员工列表?我想将加载代码保留在模型中。
我想总结一下我要问的是,在让视图模型反映这些变化的同时,模型与模型交互的正确方法是什么?
I am writing a sample app in WPF and I'd like the Model to be easily reusable in a WinForms app so I'd like to keep WPF specific stuff like INotifyChanged and DependencyObjects out of it.
If a Model class has a List of some other Model class, how do I implement the corresponding ObserveableCollection in the View-Model so I can keep my bindings up to date?
A use case for this would be if I have a Boss model object who has a list of Employee's. I create a Boss object, but I load the list of Employees asynchronously, how do I know when the list of Employees has been retrieved and populated? I would like to keep the loading code inside of the Model.
I suppose to summarize what I'm asking is what's the proper way to have Model to Model interactions whilst having the View-Model reflect these changes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的模型需要提供更改通知。您可以使用
INotifyPropertyChanged
和INotifyCollectionChanged
以不可知的方式执行此操作。与您的问题相反,这些不是 WPF 特定的接口。它们位于 System.ComponentModel 中 - 不是 WPF 命名空间或程序集。如果您确实不想使用这些接口,那么您始终可以提供自己的事件。无论哪种情况,您的视图模型都需要附加到事件,以使其自身与您的模型保持同步。
Your model will need to provide change notifications. You can do so in an agnostic fashion by using
INotifyPropertyChanged
andINotifyCollectionChanged
. Contrary to your question, these are not WPF-specific interfaces. They are inSystem.ComponentModel
- not a WPF namespace or assembly.If you really don't want to use those interfaces, then you can always provide your own events. Whatever the case, your view model will need to attach to events to keep itself up to date with your model.