MVVM视图模型的结构设计模式?
是否有推荐的 MVVM 视图模型结构设计模式,允许将不同的状态和功能动态添加到基础对象,但仍然在所有相关属性上维护 INotifyPropertyChanged?类似装饰器模式但 mvvm 就绪的东西吗?
Are there any recommended structural design patterns for MVVM view models that allow different state and functionality to be added to a base object dynamically, but still maintaining the INotifyPropertyChanged on all the related properties? Something like a decorator pattern but mvvm-ready?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。 WPF 绑定系统将使用自定义类型描述符来在运行时与 ViewModel 的属性进行交互。我之前用过这个来在 KeyValueCollection中创建键显示为集合上的属性。
这有两个重要的好处。它简化了绑定:
DataContext.SomeCollectionProperty[SomeKey]
可以简化为DataContext.SomeCollectionProperty.SomeKey
并且,如果您为数据上下文创建一个自定义类型描述符,DataContext.SomeKey
,这非常简单。它修复了我认为的错误——即使属性为空,也会呈现格式字符串。使用 CTD,您可以跳过 null(和 DBNull)属性,确保在该属性不存在时不会呈现格式字符串:
假设您有一个
double?
,您必须将其呈现为美元金额。如果您使用以下绑定:{Binding Price, FormatString='Price: {0:c}'}
并且 Price 为 null,您将在 UI 中看到以下内容:Price: $
。这太丑了。但是,如果Price
是 UI 上基于 PropertyDescriptor 的属性,则当 Price 为 null 时,您可以选择不通过 CTD 报告此属性。这根本阻止了格式字符串的呈现。MSDN 上有一个关于用 CTD 修饰类型的非常好的链接。
Yes. The WPF binding system will use a custom type descriptor to interact with the properties of your ViewModel at runtime. I've used this before to make keys in a KeyValueCollection<T> appear as properties on the collection.
This has two important benefits. It simplifies binding:
DataContext.SomeCollectionProperty[SomeKey]
can be simplified toDataContext.SomeCollectionProperty.SomeKey
and, if you make a custom type descriptor for the data context,DataContext.SomeKey
which is about as simple as it gets.And it fixes what I consider a bug--format strings are rendered even when the property is null. Using a CTD, you can skip null (and DBNull) properties, ensuring that format strings won't be rendered if the property doesn't exist:
Imagine you have a
double?
that you must render as a dollar amount. If you use the following binding:{Binding Price, FormatString='Price: {0:c}'}
and the Price is null, you get the following in your UI:Price: $
. This is ugly. However, ifPrice
is a PropertyDescriptor-based property on your UI, when the Price is null, you can opt to not to report this property via your CTD. This prevents the format string from being rendered at all.Here's a pretty good link at MSDN about decorating your types with a CTD.
根据我的实验,您可以使用 .NET 4 中的 ExpandoObject 来处理您想要的内容。 ExpandoObject 实现 INPC。我一直在基于 ExpandoObject 创建一个 DynamicViewModel,它执行一些其他操作,例如计算彼此依赖的属性和委托命令注册。
From my experimentation, you can use the ExpandoObject in .NET 4 to handle what you want. ExpandoObject implements INPC. I've been creating a DynamicViewModel based on the ExpandoObject that does a few other things like calculated Properties that have dependencies on each other and Delegate Command registration.