在 MVVM 中,如何将视图逻辑置于模型之外,并将业务逻辑置于视图模型之外?
我不太清楚如何让视图模型收到模型中更改的通知,而无需在模型中添加一堆特定于 UI 的内容(例如 INotifyProperyChanged 和 INotifyCollectionChanged),或者创建大量不同的事件并执行一堆感觉的事情就像它们是 UI 特定的并且应该远离模型一样。
否则,我只需要复制视图模型中的所有业务逻辑以确保所有内容都是最新的,那么拥有模型的意义何在?
我的模型中棘手的问题之一是“类别”类的属性。 您可以将其视为树结构,并且属性是所有叶节点的后代。 在模型中,属性是通过它的所有子项递归地动态生成的,这一切都很好。 然而,视图模型需要绑定到该属性,并且需要知道它何时发生变化。 我应该更改模型以适应视图模型吗? 如果我这样做,那么视图模型此时不会真正执行任何操作,模型会引发所有必要的更改通知,并且视图可以直接绑定到模型。 另外,如果该模型是我没有来源的东西,我将如何解决这个问题?
I can't quite figure out how to get the view model to be notified of changes in the model without adding a bunch of UI specific stuff like INotifyProperyChanged and INotifyCollectionChanged in my model or create tons of different events and do a bunch of things that feel like they're UI specific and should stay out of the model.
Otherwise I'd just have to duplicate all the business logic in the view-model to make sure everything is up to date, and then what's the point of having the model then?
One of the tricky ones that I have in my model is a property of a "Category" class. You can think of it as a tree structure and the property is all leaf-node descendants. Well in the model that property is generated on the fly recursively through all it's children, which is all fine and good. The view-model however needs to bind to that property and needs to know when it changes. Should I just change the model to accommodate the view-model? If I do then the view-model doesn't really do anything at this point, the model raises all the necessary notifications of changes and the view can just bind straight to the model. Also if the model was something I didn't have the source to, how would I get around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不同意
INotifyPropertyChanged
和INotifyCollectionChanged
是特定于 UI 的。 它们位于不依赖于任何特定 UI 堆栈的命名空间和程序集中。 出于这个原因,我通常将这种行为尽可能地放在系统的底层(通常是数据层)。如果出于某种原因您不想将其置于该级别,也没关系。 您可以将其放在更高的级别,例如服务或 UI 层。 但是,您需要确保对数据结构的所有更改也通过该层发生。
I disagree that
INotifyPropertyChanged
andINotifyCollectionChanged
are UI-specific. They are in namespaces and assemblies that are not tied to any particular UI stack. For that reason, I typically put that kind of behavior as low in the system as I can (usually the data layer).If there's some reason you don't want to put it at that level, that's fine. You can put it in at a higher level such as the service or UI layer. However, you need to make sure all changes to the data structures occur through that layer also.