如何观察转换后的集合?
我将一个集合 ObservableCollection
绑定到控制器上的依赖属性,但我通过 IValueConverter 运行它以使其变为 ObservableCollection
所以;我是否必须在转换器中连接事件处理程序才能手动保持转换后的集合与原始集合同步,或者是否有更好的方法来处理此问题?我想如果不实际创建一个新集合,我就无法进行转换?或者我可以以某种巧妙的方式进行绑定,这样我就不必进行转换了吗?
I bind a collection ObservableCollection<Foo>
to a dependency property on my controller, but I run it through an IValueConverter to make it ObservableCollection<object>
instead, which is what my controller expect. The conversion works fine - I create an ObservableCollection<object>
and fill it with all the Foo's from the original list. This however brings a problem which is that now I'm observing on the collection created in the value converter, and hence doesn't see any of the changes to the original collection.
So; do I have to hook up eventhandlers in the converter to manually keep the converted collection in sync with the original one, or is there a better way to handle this? I guess I can't do the convertion without actually creating a new collection? Or can I do the binding in some clever way such that I don't have to do the convert?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道这是否有帮助,但通常在 ViewModel 中,我声明
IList
或另一个不太具体的接口作为属性类型,而不是特定的类型。然后我可以将准所有集合和列表绑定到该属性。
设置属性后,我会检查它是否实现了 INotifyPropertyChanged,如果是,我会附加一个 CollectionChanged-EventHandler。当属性发生新更改时,我从旧的 INotifyPropertyChanged(如果是)中删除 EventHandler。
这样做的缺点是,ViewModel 必须准备好查看非预期类型的对象。但这通常是一项简单的工作。
I don't know if it helps, but often in a ViewModel, I declare
IList
or another less specific interface as the property type instead of a specific one.Then I can bind quasi all collections and lists to this propery.
While the property is set, I check if it Implements
INotifyPropertyChanged
and if yes, I attach an CollectionChanged-EventHandler. When the property has changed newly, I remove the EventHandler from the oldINotifyPropertyChanged
(if it was).The drawback of this is, that the ViewModel must be prepared to see objects other types than expected. But this is normally a simple job.
如果我理解正确的话,您正在绑定某种不通过创建新的 ObservableCollection 的转换器实现 INotifyCollectionChanged 的 ICollection。在这种情况下,您将不会从现在断开连接的集合中获得任何好处。
是否可以直接绑定您的集合(无需转换)并直接在您的对象上实现 INotifyPropertyChanged 和/或 INotifyCollectionChanged ?
If i understand correctly you are binding some sort of ICollection that does not implement INotifyCollectionChanged through a converter that creates a new ObservableCollection. In that case you would not get any benefit from the now disconnected collection.
Is it possible to bind your collection directly (without converting) and implementing INotifyPropertyChanged and/or INotifyCollectionChanged directly on your object?