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

时间:2014-05-14 11:25:33

标签: c# asp.net listbox

继承我的代码

                         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;
        }

1 个答案:

答案 0 :(得分:0)

您需要订阅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;
                }
            };