How to cast a List to an ObservableCollection in wpf?

后端 未结 4 1950
暖寄归人
暖寄归人 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

    you can do it by using extension method

    public static ObservableCollection ToObservableCollection(this IEnumerable coll)
    {
        var c = new ObservableCollection();
        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 collection = new ObservableCollection(yourList);
    

提交回复
热议问题