如何实现INotifyCollectionChanged(在向源添加项目集合后添加操作)

时间:2014-05-08 07:27:52

标签: c# winrt-xaml

我创建了自己的源,实现了inotifycollectionchanged接口...我需要在addrange之后提高collectionchanged,将更多项添加到源(不是添加一个项目时)WinRT。我有这个

     public class MySource2 : IList, INotifyCollectionChanged
   {
      private List<object> items = new List<object>(); 
      public MySource2(IEnumerable<object> initialDataSet)
      {
         items.AddRange(initialDataSet);
      }

      public IEnumerator GetEnumerator()
      {
         return items.GetEnumerator();
      }

      public void AddItems(IEnumerable<object> additionalItems)
      {
         int oldCount = Count;
         items.AddRange(additionalItems);
         this.RaiseItemsAdded(oldCount, additionalItems.ToList());
      }

      public object this[int index]
      {
         get
         {
            return items[index];
         }
         set
         {
            throw new NotImplementedException();
         }
      }

      public int Count
      {
         get
         {
            return items.Count;
         }
      }

      public event NotifyCollectionChangedEventHandler CollectionChanged;

      private void RaiseItemsAdded(int index, IList newItems)
      {
         var handlers = this.CollectionChanged;

         if (handlers != null)
         {
            var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newItems, index);

            handlers(this, args);
         }
      }

这个抛出Argument异常(参数是incorect)...我做错了什么?           }

1 个答案:

答案 0 :(得分:0)

不是告诉你如何编写你的应用程序代码,但是你考虑过一种更简单的方法吗?

public class MyList<T> : ObservableCollection<T>
{
    public void AddRange(IEnumerable<T> items)
    {
        this.AddRange(items);
        var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, items.ToList(), null);
        base.OnCollectionChanged(args);
    }

    public void RemoveRange(Func<T, bool> predicate)
    { RemoveRange(this.Where(predicate)); }

    private void RemoveRange(IEnumerable<T> items)
    {
        this.RemoveRange(items);
        var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, null, items.ToList());
        base.OnCollectionChanged(args);
    }
}

祝你好运!