Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert List to ObservableCollection?

I am a java Developer,new to C# silverlight. in this class I want to Convert the Products(List) to ObservableCollection.

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;

namespace WPListBoxImage
{
/**It seems not work,if I just change List<Product> to ObservableCollection<Product>
  public class Products : List<Product>
  {
    public Products()
    {
      BuildCollection();

    }

    private const string IMG_PATH = "../Images/";

    public ObservableCollection<Product> DataCollection { get; set; }

    public ObservableCollection<Product> BuildCollection()
    {
      DataCollection = new ObservableCollection<Product>();

      DataCollection.Add(new Product("Haystack Code Generator for .NET", 799, IMG_PATH + "Haystack.jpg"));
      DataCollection.Add(new Product("Fundamentals of N-Tier eBook", Convert.ToDecimal(19.95), IMG_PATH + "FundNTier_100.jpg"));
      DataCollection.Add(new Product("Fundamentals of ASP.NET Security eBook", Convert.ToDecimal(19.95), IMG_PATH + "FundSecurity_100.jpg"));
      DataCollection.Add(new Product("Fundamentals of SQL Server eBook", Convert.ToDecimal(19.95), IMG_PATH + "FundSQL_100.jpg"));
      DataCollection.Add(new Product("Fundamentals of VB.NET eBook", Convert.ToDecimal(19.95), IMG_PATH + "FundVBNet_100.jpg"));
      DataCollection.Add(new Product("Fundamentals of .NET eBook", Convert.ToDecimal(19.95), IMG_PATH + "FundDotNet_100.jpg"));
      DataCollection.Add(new Product("Architecting ASP.NET eBook", Convert.ToDecimal(19.95), IMG_PATH + "ArchASPNET_100.jpg"));
      DataCollection.Add(new Product("PDSA .NET Productivity Framework", Convert.ToDecimal(2500), IMG_PATH + "framework.jpg"));

      return DataCollection;
    }
  }
}

what should I do to fix it? or need to create a new class?

like image 472
Albert.Qing Avatar asked Mar 13 '12 02:03

Albert.Qing


People also ask

What is the difference between ObservableCollection and list?

The true difference is rather straightforward:ObservableCollection implements INotifyCollectionChanged which provides notification when the collection is changed (you guessed ^^) It allows the binding engine to update the UI when the ObservableCollection is updated. However, BindingList implements IBindingList.

How do you cast IEnumerable to ObservableCollection?

var myObservableCollection = new ObservableCollection<YourType>(myIEnumerable); This will make a shallow copy of the current IEnumerable and turn it in to a ObservableCollection.


1 Answers

There is a constructor in ObservableCollection that does this:

ObservableCollection<T> oc = new ObservableCollection<T>(List<T> list);
like image 185
Ahad aghapour Avatar answered Sep 22 '22 19:09

Ahad aghapour