如何将列表转换为ObservableCollection?

前端之家收集整理的这篇文章主要介绍了如何将列表转换为ObservableCollection?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是一个java开发人员,新到C#silverlight。
在这个类中,我想将产品(List)转换为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",IMG_PATH + "FundSecurity_100.jpg"));
      DataCollection.Add(new Product("Fundamentals of sql Server eBook",IMG_PATH + "Fundsql_100.jpg"));
      DataCollection.Add(new Product("Fundamentals of VB.NET eBook",IMG_PATH + "FundVBNet_100.jpg"));
      DataCollection.Add(new Product("Fundamentals of .NET eBook",IMG_PATH + "FundDotNet_100.jpg"));
      DataCollection.Add(new Product("Architecting ASP.NET eBook",IMG_PATH + "ArchASPNET_100.jpg"));
      DataCollection.Add(new Product("PDSA .NET Productivity Framework",Convert.ToDecimal(2500),IMG_PATH + "framework.jpg"));

      return DataCollection;
    }
  }
}

我该怎么办来解决?还是需要创建一个新的类?

您的产品类不应该继承任何东西。
public class Products

通过Product类的DataCollection属性访问集合中的所有项目。例如,

Products myProducts = new Products();
ObservableCollection<Product> myData = myProducts.DataCollection;

它还取决于您如何使用产品。你可以完全不用这个课,然后做一些类似的事情:

ObservableCollection<Product> Products = new ObservableCollection<Product>();
Products.Add(new Product("Haystack Code Generator for .NET",IMG_PATH + "Haystack.jpg"));
// etc...
原文链接:https://www.f2er.com/windows/373079.html

猜你在找的Windows相关文章