在IEnumerable中使用可观察收集的优点和缺点 [英] Pros and Cons of using Observable Collection over IEnumerable

查看:173
本文介绍了在IEnumerable中使用可观察收集的优点和缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想决定是否要将所有的 IEnumerable 集合切换到可观察的集合。我找不到这个很好的解释。

I am trying to decide if I want to switch all of my IEnumerable collections over to Observable Collections. I cannot find a good explanation of this. What are the Pros and Cons of the Observable Collection in understandable terms?

推荐答案

您可以决定拥有 IEnumerable< Something> 作为一些属性的类型,但使用 ObservableCollection< Something> 作为实际值。

You may decide to have IEnumerable<Something> as type of some property, but use ObservableCollection<Something> as the actual value.

如果你有这样的属性:

private IEnumerable<Something> collectionOfSomething;
public IEnumerable<Something> CollectionOfSomething
{
    get { return collectionOfSomething; }
    set
    {
        collectionOfSomething = value;
        NotifyPropertyChanged("CollectionOfSomething");
    }
}

现在您可以简单地分配给



Now you may simply assign to that property like

someViewModelObject.CollectionOfSomething = new ObservableCollection<Something>();






当您分配或绑定到集合属性例如 ItemsControl.ItemsSource ),目标对象通常检查实际属性值是否实现 INotifyCollectionChanged (what ObservableCollection )并附加一个 CollectionChanged 处理程序,以获取源集合中的更改通知。


When you assign or bind to a collection property (for example ItemsControl.ItemsSource), the target object usually checks whether the actual property value implements INotifyCollectionChanged (what ObservableCollection does) and attaches a CollectionChanged handler to get notified about changes in the source collection.

如果您以后决定使用 INotifyCollectionChanged 的其他更聪明的实现,您不需要更改所有属性类型。

If you later decide to have some other, smarter implementation of INotifyCollectionChanged you do not need to change all your property types. Just replace the assignment(s) by something like this

someViewModelObject.CollectionOfSomething = new MyVerySmartCollection<Something>();

这篇关于在IEnumerable中使用可观察收集的优点和缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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