开发者

Howto observe converted collections?

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 ac开发者_Go百科tually creating a new collection? Or can I do the binding in some clever way such that I don't have to do the convert?


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


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜