在asp.net c#中将可观察对象集合绑定到列表框

本文关键字:集合 对象 绑定 列表 观察 net asp | 更新日期: 2023-09-27 18:03:22

我的代码

                         ObservableCollection<product> pr = new ObservableCollection<product>();
    protected void Page_Load(object sender, EventArgs e)
    {
        product p = new product();
        p.PhoneMake = "Apple";
        p.PhoneModel = "4S";
        p.Price = 40;
        pr.Add(p);
        product q = new product();
        p.PhoneMake = "Apple";
        p.PhoneModel = "5S";
        p.Price = 80;
        pr.Add(q);
        lstbxProd.DataSource = pr;

没有更新列表框。我需要物品来源吗?我能做些什么?

我也试过了

     foreach (product a in pr)
        {
            lstbxProd.Items.Add(a).ToString;
        }

在asp.net c#中将可观察对象集合绑定到列表框

你需要订阅Observable集合的CollectionChanged事件。像这样的东西应该让你开始。

         ObservableCollection<Product> products = new ObservableCollection<Product>();
           //Replace the lst with your control
                var lst = new List<Product>();
            products.CollectionChanged += (sender, eve) =>
            {
                switch (eve.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        //add to your control here    
                        lst.Add((Product) eve.NewItems[0]);
                        break;
                    case NotifyCollectionChangedAction.Remove:
                         //add implementation here
                        break;
                    case NotifyCollectionChangedAction.Replace:
                        break;
                    case NotifyCollectionChangedAction.Move:
                        break;
                    case NotifyCollectionChangedAction.Reset:
                        break;
                }
            };