How to cast a List to an ObservableCollection in wpf?

后端 未结 4 1951
暖寄归人
暖寄归人 2021-02-05 11:09

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

I understand I can iterate over the list and

相关标签:
4条回答
  • 2021-02-05 11:44

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

    ObservableCollection<MyType> obsCollection = new ObservableCollection<MyType>(myList);
    
    0 讨论(0)
  • 2021-02-05 11:44

    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<YourObject> collection = new ObservableCollection<YourObject>(yourList);
    
    0 讨论(0)
  • 2021-02-05 11:53

    ObservableCollection has Conttructor for IEnumerable<T> ObservableCollection

    ObservableCollection<yourType> observable = 
            new ObservableCollection<yourType>(yourListObject);
    
    0 讨论(0)
  • 2021-02-05 11:55
    var _oc = new ObservableCollection<ObjectType>(_listObjects);
    
    0 讨论(0)
提交回复
热议问题