Howto observe converted collections?

為{幸葍}努か 提交于 2019-12-11 06:38:54

问题


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?


回答1:


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 old INotifyPropertyChanged (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.

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);
    }



回答2:


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?



来源:https://stackoverflow.com/questions/3675922/howto-observe-converted-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!