如何将List 转换为wpf中的ObservableCollection ?

时间:2022-03-23 19:42:39

I am in wpf, and have a generic list: List. Now I wish to cast it to a generic observable collections: ObservableCollection.

我在wpf,并有一个通用列表:列表。现在我希望将它转换为通用的可观察集合:ObservableCollection。

I understand I can iterate over the list and add each individual item to the Observable collection. However, it seems to me there has to be a built-in way of doing this.

我知道我可以迭代列表并将每个单独的项添加到Observable集合中。但是,在我看来,必须有一种内置的方式来做到这一点。

4 个解决方案

#1


30  

If you JUST want to create an ObservableCollection from a List, then all you need to do is

如果您只想从List创建一个ObservableCollection,那么您需要做的就是

ObservableCollection<MyType> obsCollection = new ObservableCollection<MyType>(myList);

#2


3  

var _oc = new ObservableCollection<ObjectType>(_listObjects);

#3


2  

ObservableCollection has Conttructor for IEnumerable<T> ObservableCollection

ObservableCollection具有IEnumerable ObservableCollection的Conttructor

ObservableCollection<yourType> observable = 
        new ObservableCollection<yourType>(yourListObject);

#4


2  

you can do it by using extension method

你可以使用扩展方法来做到这一点

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll)
{
    var c = new ObservableCollection<T>();
    foreach (var e in coll) c.Add(e);
    return c;
}

or you can use this constructor The elements are copied onto the ObservableCollection in the same order they are read by the enumerator of the list.

或者您可以使用此构造函数将元素按照列表的枚举器读取的顺序复制到ObservableCollection中。

ObservableCollection<YourObject> collection = new ObservableCollection<YourObject>(yourList);

#1


30  

If you JUST want to create an ObservableCollection from a List, then all you need to do is

如果您只想从List创建一个ObservableCollection,那么您需要做的就是

ObservableCollection<MyType> obsCollection = new ObservableCollection<MyType>(myList);

#2


3  

var _oc = new ObservableCollection<ObjectType>(_listObjects);

#3


2  

ObservableCollection has Conttructor for IEnumerable<T> ObservableCollection

ObservableCollection具有IEnumerable ObservableCollection的Conttructor

ObservableCollection<yourType> observable = 
        new ObservableCollection<yourType>(yourListObject);

#4


2  

you can do it by using extension method

你可以使用扩展方法来做到这一点

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll)
{
    var c = new ObservableCollection<T>();
    foreach (var e in coll) c.Add(e);
    return c;
}

or you can use this constructor The elements are copied onto the ObservableCollection in the same order they are read by the enumerator of the list.

或者您可以使用此构造函数将元素按照列表的枚举器读取的顺序复制到ObservableCollection中。

ObservableCollection<YourObject> collection = new ObservableCollection<YourObject>(yourList);