2011-07-29 103 views
16

我有一个ObservableCollection,我可以添加和删除集合中的项目。但我无法替换集合中的现有项目。有一种方法可以替换项目,并在我的绑定组件上反映出来。Observable Collection替换项目

System.Collections.Specialized.NotifyCollectionChangedAction.Replace 

任何人都可以告诉我如何做到这一点?

+0

可能的重复[如何更新ObservableCollection类中的单个项?](http://stackoverflow.com/questions/6781192/how-do-i-update-a-single-item-in-an -observablecollection级) – KyleMit

回答

47
collection[someIndex] = newItem; 
+0

我这样做achive通过实施这个类 公共类MyObservableCollection :的ObservableCollection { 公共MyObservableCollection(){ } 公共MyObservableCollection(名单集合) { MyObservableCollection MB =新的MyObser vableCollection (); for(int x = 0; x thewayman

+4

你不需要自己创建类。你可以写'collection [someIndex] = newItem'。 – SLaks

2

更新:Indexer使用重写的SetItem并通知有关更改。

我考虑使用索引的答案可能是错,因为这个问题是关于更换并通知

只是为了澄清:ObservableCollection<T>使用索引从其基部Collection<T>类,而这又是List<T>的包装,这是简单T阵列的包装。并且在ObservableCollection实现中没有对索引器方法的替代。

所以,当你使用索引在的ObservableCollection更换一个项目从收集调用下面的代码类:

public T this[int index] { 
     get { return items[index]; } 
     set { 
      if(items.IsReadOnly) { 
       ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); 
      } 

      if (index < 0 || index >= items.Count) { 
       ThrowHelper.ThrowArgumentOutOfRangeException(); 
      } 

      SetItem(index, value); 
     } 

它只是检查边界,并呼吁使用名单底层的索引SetItem等级:

protected virtual void SetItem(int index, T item) { 
     items[index] = item; 
    } 

在分配期间没有呼叫CollectionChanged事件,因为底层集合对此一无所知。

但是,当您使用SetItem方法,它是从的ObservableCollection类叫做:

protected override void SetItem(int index, T item) 
    { 
     CheckReentrancy(); 
     T originalItem = this[index]; 
     base.SetItem(index, item); 

     OnPropertyChanged(IndexerName); 
     OnCollectionChanged(NotifyCollectionChangedAction.Replace, originalItem, item, index); 
    } 

分配后,它调用OnCollectionChanged方法,它触发CollectionChanged事件与NotifyCollectionChangedAction.Replace动作参数。

protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) 
    { 
     if (CollectionChanged != null) 
     { 
      using (BlockReentrancy()) 
      { 
       CollectionChanged(this, e); 
      } 
     } 
    } 

这样的结论:从继承的ObservableCollection自定义类和调用base.SetItem()值得一试Replace方法的想法。

+1

运算符[]使用ObservableCollection的重写方法SetItem –

+0

感谢您的澄清。 –