NotifyCollectionChangedAction.Reset不起作用

时间:2019-11-07 15:25:18

标签: c# wpf observablecollection

我有两个ObservableCollection,分别名为BuyOrdersSellOrders。如果我以这种方式从其中一项中删除项目:

var list = order.OrderType == OrderType.Buy ? BuyOrders : SellOrders;
var o = list.Where(x => x.OrderNo == order.OrderNo).First();
list.Remove(o);

ObservableCollection.CollectionChanged事件有效。但是,如果我要更新这样的项目:

var list = order.OrderType == OrderType.Buy ? BuyOrders : SellOrders;
var o = list.Where(x => x.OrderNo == order.OrderNo).First();
o.Price = order.Price;
o.Quantity = order.Quantity;

CollectionChanged事件不起作用!它不是有效的Reset吗?

我的代码有什么问题吗?


编辑

这是BuyOrders的处理程序:

void BuyChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    AllOrder order = null;
    switch (e.Action)
    {
        case NotifyCollectionChangedAction.Add:
            try { order = e.NewItems[0] as AllOrder; }
            catch (Exception) { return; }
            if (order.ItemCode == ItemCode) Buys = GetOrders(ClientCode.BuyOrders).OrderByDescending(x => x.Price);
            break;

        case NotifyCollectionChangedAction.Remove:
        case NotifyCollectionChangedAction.Reset:
            Buys = GetOrders(ClientCode.BuyOrders).OrderByDescending(x => x.Price);
            break;
    }
}

我对SellOrders有类似的处理程序

我正在使用的ObservableCollection被命名为AsyncObsetion,并已通过以下方式实现:

public class AsyncObsetion<T> : ObservableCollection<T>
{
    private SynchronizationContext context = SynchronizationContext.Current;
    public AsyncObsetion() { }
    public AsyncObsetion(IEnumerable<T> list) : base(list) { }

    void RaiseCollectionChanged(object param) => base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param);
    void RaisePropertyChanged(object param) => base.OnPropertyChanged((PropertyChangedEventArgs)param);

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (SynchronizationContext.Current == context) RaiseCollectionChanged(e);
        else context.Send(RaiseCollectionChanged, e);
    }

    protected override void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (SynchronizationContext.Current == context) RaisePropertyChanged(e);
        else context.Send(RaisePropertyChanged, e);
    }      
}

摆脱App.Current.Dispatcher.Invoke

1 个答案:

答案 0 :(得分:1)

您应该做的是订阅Orders中每个订单的PropertyChanged,并触发CollectionChanged事件

foreach(var order in orders) {

  order.PropertyChanged += (sender, args) {
       // if you need to to only respond to a certain property
       // if (args.PropertyName != nameof(Order.Property)) return; 
       // do any other code here
       Orders.RaiseCollectionChanged(sender);
    };

}