在 Silverlight 中绑定来自 WCF 的对象集合的良好模式是什么?
我有一个关于 Silverlight WCF 数据绑定模式的问题:
有很多关于如何在 XAML 中使用 {Binding} 表达式绑定数据、如何对 WCF 服务进行异步调用、在 UI 中设置元素的 DataContext 属性的示例、如何使用ObservableCollections和INotifyPropertyChanged、INotifyCollectionChanged等。
背景: 我正在使用 MVVM 模式,并且有一个 Silverlight ItemsControl,其 ItemsSource 设置为我的 ViewModel 对象上的 ObservableCollection 属性。我的观点当然是具有 {Binding} 的 XAML。假设模型对象称为“Metric”。我的 ViewModel 定期调用返回 ObservableCollection 的 WCF 服务。 MetricInfo 是数据传输对象 (DTO)。
我的问题有两个:
- 有没有办法避免将 MetricInfo 的每个属性复制到模型类 - Metric?
- 当 WCF 调用完成时,有什么方法可以确保我同步本地 ObservableCollection 中的项目和 WCF 调用的结果 - 而不必首先清除本地集合中的所有项目,然后添加所有来自 WCF 调用结果的?
谢谢, 克里希纳
I've got a question about a Silverlight WCF Databinding pattern:
There are many examples about how to bind data using {Binding} expressions in XAML, how to make async calls to a WCF service, set the DataContext property of a element in the UI, how to use ObservableCollections and INotifyPropertyChanged, INotifyCollectionChanged and so on.
Background:
I'm using the MVVM pattern, and have a Silverlight ItemsControl, whose ItemsSource is set to an ObservableCollection property on my ViewModel object. My view is of course the XAML which has the {Binding}. Say the model object is called 'Metric'. My ViewModel periodically makes calls to a WCF service that returns ObservableCollection. MetricInfo is the data transfer object (DTO).
My question is two-fold:
- Is there any way to avoid copying each property of MetricInfo to the model class - Metric?
- When the WCF calls completes, is there any way to make sure I sync the items which are in both my local ObservableCollection and the result of the WCF call - without having to first clear out all the items in the local collection and then add all the ones from the WCF call result?
thanks,
Krishna
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1)我已经通过这样的构造函数完成了映射:
然后将属性从 DTO 映射到实体,这当然是您要避免的。是的,这是一项工作,但对我来说效果很好。另一种方法是使用像 AutoMapper 这样的对象映射器
2)我想你可能有某种比较逻辑对集合进行更新和插入。对于我来说,我已经完成了您在问题中所描述的明确并添加了内容。它很简单,很短,我没有遇到任何问题。
1) I have done the mapping through a constructor like this:
then map the properties from the DTO to the entity which of course is what you are trying to avoid. Yes, this is a bit of work but for me it has worked out very well. The alternative could be to use a object mapper like AutoMapper
2) I suppose you could have some kind of comparison logic to do updates and inserts into the collection. For me, I have done the clear and add which you describe in you question. It's simple, short and I haven't had any issues with it.