添加唯一元素并自动更新C#中的ObservableCollection

时间:2017-08-24 10:18:51

标签: c# list listview observablecollection

我有一个绑定到listView的ObservavebleColection。基本上,此集合必须跟上服务器中的每个更改,并以字符串格式接收更新。

我的代码解析字符串并将元素添加到集合中,但是我找不到删除元素的方法。如何在服务器上删除或更改元素时更新集合?

这是我的代码:

public static ObservableCollection<TransactionDetails> offerList = new ObservableCollection<TransactionDetails>();

public async static Task<ObservableCollection<TransactionDetails>> getOfferList()
    {
        // Start getting Offers

        string Offer = await BedpAPI_V1.getOfferList();

        string[] splitedResponse = Offer.Split(new[] { "@@@@" }, StringSplitOptions.RemoveEmptyEntries);

        foreach (string response in splitedResponse) {
            string[] splitedMessage = response.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

            offer.TransactionID = Convert.ToInt32(splitedMessage[0]);
            offer.Seller = splitedMessage[1];
            offer.Cost = Convert.ToDouble(splitedMessage[2]);
            offer.Duration = Convert.ToInt16(splitedMessage[3]);
            offer.Delay = Convert.ToInt16(splitedMessage[4]);
            offer.Capacity = Convert.ToDouble(splitedMessage[5]);
            offer.Availability = Convert.ToDouble(splitedMessage[6]);

            if (currentOffer <= offer.TransactionID)
            {
                offerList.Add(new TransactionDetails() { TransactionID = offer.TransactionID, Seller = offer.Seller, Cost = offer.Cost, Duration = offer.Duration, Delay = offer.Delay, Capacity = offer.Capacity, Availability = offer.Availability });

                currentOffer++;
            }
        }
        return offerList;
    }

2 个答案:

答案 0 :(得分:0)

如果ListView与ObservavebleColection<>绑定,则在修改元素时,您可以自行触发OnCollectionChanged事件。 假设您使用[]修改元素:

public class MyCollection : ObservableCollection<MyClass>
{
    public new MyClass this[int index]
    {
        get { return base[index]; }
        set 
        {
            base[index] = value;
            base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
    }
}

更新:

首先,您可能希望绑定您的集合,如:

myCollection = MyFunction();
MyListView.ItemsSource = myCollection;

如果您更改集合中的项目,请执行以下操作:

myCollection[index] = someNewItem;

然后您可以更新列表视图,如:

MyListView.Refresh();

但建议使用一些动态绑定。

答案 1 :(得分:0)

我通过在解析splitedResponse之前清除每次调用的集合来解决问题 - 因为Clear()抛出了一个unheld异常,不得不在throw catch块中处理它:

try 
{
   offerList.Clear();
}

catch (Exception ex) {

   offerList.Clear();
   Console.WriteLine(ex.Message);
}