HOWTO观察转换后的集合? [英] Howto observe converted collections?

查看:135
本文介绍了HOWTO观察转换后的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绑定的集合的ObservableCollection<富> 来上我的控制器依赖项属性,但我通过的IValueConverter运行它,使之的ObservableCollection<对象> 而不是,这是我的控制器期望。转换工作正常 - 我创建一个的ObservableCollection<对象> ,并从原来的列表中的所有Foo的填充。但是,这带来了一个问题,就是现在我的观察,在值转换器创建集合,因此并没有看到任何的改变原有集合。

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?

推荐答案

我不知道是否有帮助,但往往在一个视图模型,我宣布的IList 或其它那么具体的接口作为属性类型,而不是一个具体的问题。

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.

虽然该属性设置,我检查它是否实现 INotifyPropertyChanged的,如果是,我附上一个CollectionChanged-事件处理程序。当属性发生新的变化,我从旧删除事件处理程序 INotifyPropertyChanged的(如果是)。

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 old INotifyPropertyChanged (if it was).

这样做的缺点是,该视图模型必须ppared看物体其他类型的比预期的$ P $。但是,这通常是一个简单的工作。

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.

void YourDPValueChanged(DependencyPropertyChangedEventArgs e) {
    INotifyCollectionChanged newCollection = e.NewValue as INotifyCollectionChanged;
    INotifyCollectionChanged oldCollection = e.OldValue as INotifyCollectionChanged;
    if (null != newCollection) {
        newCollection.CollectionChanged += new NotifyCollectionChangedEventHandler(Collection_CollectionChanged);
    }
    if (null != oldCollection) {
        oldCollection.CollectionChanged -= new NotifyCollectionChangedEventHandler(Collection_CollectionChanged);
    }

这篇关于HOWTO观察转换后的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆