Convert List to ObservableCollection in WP7

后端 未结 10 859
不知归路
不知归路 2020-12-25 10:10

I don\'t know if it\'s just too late or what, but I don\'t see how to do this...

What I\'m expecting to do, and what the object browser says is there, is this:

相关标签:
10条回答
  • 2020-12-25 10:20

    Apparently, your project is targeting Windows Phone 7.0. Unfortunately the constructors that accept IEnumerable<T> or List<T> are not available in WP 7.0, only the parameterless constructor. The other constructors are available in Silverlight 4 and above and WP 7.1 and above, just not in WP 7.0.

    I guess your only option is to take your list and add the items into a new instance of an ObservableCollection individually as there are no readily available methods to add them in bulk. Though that's not to stop you from putting this into an extension or static method yourself.

    var list = new List<SomeType> { /* ... */ };
    var oc = new ObservableCollection<SomeType>();
    foreach (var item in list)
        oc.Add(item);
    

    But don't do this if you don't have to, if you're targeting framework that provides the overloads, then use them.

    0 讨论(0)
  • 2020-12-25 10:24
    ObservableCollection<FacebookUser_WallFeed> result = new ObservableCollection<FacebookUser_WallFeed>(FacebookHelper.facebookWallFeeds);
    
    0 讨论(0)
  • 2020-12-25 10:26

    To convert List<T> list to observable collection you may use following code:

    var oc = new ObservableCollection<T>();
    list.ForEach(x => oc.Add(x));
    
    0 讨论(0)
  • 2020-12-25 10:27

    Extension method from this answer IList<T> to ObservableCollection<T> works pretty well

    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable) {
      var col = new ObservableCollection<T>();
      foreach ( var cur in enumerable ) {
        col.Add(cur);
      }
      return col;
    }
    
    0 讨论(0)
  • 2020-12-25 10:28

    I made an extension so now I can just load a collection with a list by doing:

    MyObservableCollection.Load(MyList);
    

    The extension is:

    public static class ObservableCollectionExtension
    {
      public static ObservableCollection<T> Load<T>(this ObservableCollection<T> Collection, List<T> Source)
      {
              Collection.Clear();    
              Source.ForEach(x => Collection.Add(x));    
              return Collection;
       }
    }
    
    0 讨论(0)
  • 2020-12-25 10:32

    Use this:

    List<Class1> myList;
    ObservableCollection<Class1> myOC = new ObservableCollection<Class1>(myList);
    
    0 讨论(0)
提交回复
热议问题