在类模型上使用 DependencyProperty 和 ObservableCollection
我刚刚开始使用 MVVM 的 WPF,所以请原谅任何误解。我有一个模型(不是视图模型,而是实际模型),该模型在类内有许多 List,这些类位于其他 List 中制作数据树的类中。
重要的是,数据应该是 XML 可序列化的,目前使用常规属性和列表做到这一点没有问题。
这个类的视图模型比我预期的要多得多,我正在考虑将部分或全部列表转换为 ObservableCollections,这样做的优点和缺点是什么?
另外,“可绑定模型”中最好的是什么,NotifyPropertyChange 还是 DependencyProperties?我认为 DependencyProperty 会带来一些内存增益,因为许多对象将在大多数属性上使用默认值,一般性能如何,序列化有任何问题吗?
问候,
I just starting on WPF with MVVM, so forgive any misconceptions. I have a model (not a view model but the actual model) that has many List inside classes that are in other List making trees of data.
Important, the data should be XML Serializabled, currently there is no problem doing that with regular properties and List.
The View Model of this class is taking a lot more work than I expected and I'm thinking on converting some or maybe all of the List to ObservableCollections, what are the pros and cons of that?
Also, what would be best in a "bindable model", NotifyPropertyChange or DependencyProperties? I think there would be some memory gains with DependencyProperty since many objects will use default values on most of the properties, what about performance in general, and has it any problems with serialization?
Regards,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与
List
相比,ObservableCollection
的开销要大一些,但它确实使操作变得更容易,因为数据可以直接绑定到模型集合。我不会在您的模型中使用 DependencyProperties。这依赖于 WPF 库,并且非常特定于平台。如果您希望能够将数据直接绑定到模型,那么实现 INotifyPropertyChanged 是一种合理的方法。
但是,在进行任何这些更改之前,您确实应该停下来花一分钟时间。如果您更改模型类主要是为了在视图中使用它们,那么您就违反了 MVVM(以及大多数其他架构模式)的基本原则。这里的主要目标之一是您的模型不知道正在使用的表示层 - 这使得它在未来更加灵活,因为您可以更改表示层而不需要更改您的模型。
There is a bit more overhead in
ObservableCollection<T>
when compared toList<T>
, but it does make it easier as data binding directly to your model collections will work.I would not use DependencyProperties within your model. This is taking a dependency on the WPF libraries, and very platform specific. If you want to be able to data bind directly to your model, implementing
INotifyPropertyChanged
is a reasonable approach.However, you really should stop and take a minute before making any of these changes. If you're changing your model classes primarily to use them in your View, you're violating the basic principles of MVVM (and most other architectural patterns). One of the main goals here is that your Model is unaware of the presentation layer being used - this makes it more flexible in the future, as you can change presentation layers without changing your model at all.