当在一个模型-视图-视图模型架构的WPF应用程序中实现ViewModel时,似乎有两个主要的选择:如何使它可数据化。我已经看到实现使用DependencyProperty属性的视图要绑定,我已经看到ViewModel实现INotifyPropertyChanged代替。
我的问题是,什么时候我应该更喜欢其中一个?有什么性能差异吗?把ViewModel依赖项交给WPF真的是个好主意吗?在做设计决定时,我还需要考虑什么?
当在一个模型-视图-视图模型架构的WPF应用程序中实现ViewModel时,似乎有两个主要的选择:如何使它可数据化。我已经看到实现使用DependencyProperty属性的视图要绑定,我已经看到ViewModel实现INotifyPropertyChanged代替。
我的问题是,什么时候我应该更喜欢其中一个?有什么性能差异吗?把ViewModel依赖项交给WPF真的是个好主意吗?在做设计决定时,我还需要考虑什么?
当前回答
选择完全取决于您的业务逻辑和UI抽象级别。如果你不想好好分开,那么DP可以帮你。
DependencyProperties将主要适用于VisualElements级别,所以如果我们为每个业务需求创建大量的dp并不是一个好主意。DP的开销也比INotifyPropertyChanged大。当你设计WPF/Silverlight时,试着把UI和ViewModel完全分开,这样我们就可以随时改变布局和UI控件(基于主题和样式)。
请参考这篇文章- https://stackoverflow.com/questions/275098/what-applications-could-i-study-to-understand-datamodel-view-viewmodel。该链接有很多参考模型-视图-视图模型模式,这与本文的讨论非常相关。
其他回答
选择完全取决于您的业务逻辑和UI抽象级别。如果你不想好好分开,那么DP可以帮你。
DependencyProperties将主要适用于VisualElements级别,所以如果我们为每个业务需求创建大量的dp并不是一个好主意。DP的开销也比INotifyPropertyChanged大。当你设计WPF/Silverlight时,试着把UI和ViewModel完全分开,这样我们就可以随时改变布局和UI控件(基于主题和样式)。
请参考这篇文章- https://stackoverflow.com/questions/275098/what-applications-could-i-study-to-understand-datamodel-view-viewmodel。该链接有很多参考模型-视图-视图模型模式,这与本文的讨论非常相关。
根据WPF性能指南,DependencyObjects肯定比实现INotifyPropertyChanged的POCOs性能更好:
http://msdn.microsoft.com/en-us/library/bb613546.aspx
我更喜欢一种更直接的方法,我在没有INotifyPropertyChanged的表示模型中写过。使用数据绑定的替代方案,您可以直接绑定到CLR属性,而不需要任何簿记代码。您只需在视图模型中编写普通的。net代码,当数据模型发生变化时,它就会更新。
依赖属性旨在支持在UI元素上绑定(作为目标),而不是作为数据绑定的源,这就是INotifyProperty的作用。从纯粹的角度来看,你不应该在ViewModels上使用DP。
"In order to be the source of a binding, a property does not need to be a dependency property; you can use any CLR property as a binding source. However, in order to be the target of a binding, the property must be a dependency property. For a one-way or two-way binding to be effective, the source property must support change notifications that propagate to the binding system and thus the target. For custom CLR binding sources, this means that the property must support INotifyPropertyChanged. Collections should support INotifyCollectionChanged."
所有依赖对象都不能被序列化(这可能会妨碍ViewModels和DTO (POCO)的使用。
与WPF相比,Silverlight中的DP有一些不同之处。
http://msdn.microsoft.com/en-us/library/cc221408 (v = VS.95) . aspx
http://msdn.microsoft.com/en-us/library/cc903933 (VS.95) . aspx
选择DependencyObject的原因只有一个——绑定会工作得更好。只是尝试一个ListBox和TextBox的例子,用INotifyPropertyChanged属性与DependencyProperty的数据填充列表,并从TextBox编辑当前项目…