2012-02-20 4 views
0

ObservableCollection은 colleciton에서 항목을 추가, 제거 또는 업데이트 할 때 CollectionChanged 이벤트를 제공하지만 새 항목을 컬렉션을 발생시키는 컬렉션에 추가 할 때마다 예를 들어 개별 항목 변경에 대한 이벤트를 발생시킵니다.CollectionChanged 이벤트

이제 컬렉션에 대한 모든 수정을 완료 한 후에 이벤트를 발생시키는 것이 좋습니다. 예를 들어, 2 개의 항목을 추가하고 하나의 항목을 삭제하고 2 개의 항목을 업데이트해야합니다. CollectionChanged 이벤트는 이러한 모든 추가, 삭제 및 업데이트를 완료 한 후에 만 ​​실행해야합니다.

또는은, 내가 새 컬렉션을 할당 할 때 예를 들어, CollectionChanged을 인상 할, 지금, 모든 수정을 새 컬렉션이 있다고 가정

ObservableCollection<string> mainCollection; //assume it has some items 
mainCollection = updatedCollection; // at this point I want to raise the event. 

여러분의 소중한 의견을주십시오. 당신이 오히려 ObservableCollection에 클래스 해고 이벤트가 아닌 mainCollection 변수에 할당을 지켜보고있을 것 같은

감사합니다,

BHavik

답변

1

보인다. 이런 식으로 뭔가 :

 private ObservableCollection<MyItemType> _mainCollection; 
     public ObservableCollection<MyItemType> MainCollection 
     { 
      get 
      { 
       return _mainCollection; 
      } 
      set 
      { 
       _mainCollection = value; 
       TriggerMyEvent(); // do whatever you like here 
      } 
     } 
+0

내 이벤트를 발생시키고 싶지 않다. ObservableColleciton의 CollectionChangedEvent 만 사용하고 싶다. –

+0

@RaoBHavik : 당신이 요구하는 것은 불가능합니다. –

+0

ObservableColleciton 대신 다른 옵션을 선택할 수 있으므로 내 요구 사항을 충족합니다. –

2
그것은 당신이 작성하는 방법을 작동하지 않습니다

, 원인은 mainCollection 개체의 이벤트에 가입 한 후 전체를 다른 목적은 단지 같은 변수 이름을 referencng로 교체 한 것입니다 . 당신은 모음을 할당 할 수 있지만 주요 컬렉션에 업데이트 된 콜렉션의 모든 요소를 ​​추가 할 필요가 없습니다

편집 : ObservableCollection에 대한 AddRange :

using System.Collections.Specialized; 
using System.Collections.Generic; 

namespace System.Collections.ObjectModel 
{ 

/// <summary> 
/// Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed. 
/// </summary> 
/// <typeparam name="T"></typeparam> 
public class ObservableCollection<T> : System.Collections.ObjectModel.ObservableCollection<T> 
{ 

    /// <summary> 
    /// Adds the elements of the specified collection to the end of the ObservableCollection(Of T). 
    /// </summary> 
    public void AddRange(IEnumerable<T> collection) 
    { 
     foreach (var i in collection) Items.Add(i); 
     OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add), collection.ToList()); 
    } 

    /// <summary> 
    /// Removes the first occurence of each item in the specified collection from ObservableCollection(Of T). 
    /// </summary> 
    public void RemoveRange(IEnumerable<T> collection) 
    { 
     foreach (var i in collection) Items.Remove(i); 
     OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove), collection.ToList()); 
    } 

    /// <summary> 
    /// Clears the current collection and replaces it with the specified item. 
    /// </summary> 
    public void Replace(T item) 
    { 
     ReplaceRange(new T[] { item }); 
    } 
    /// <summary> 
    /// Clears the current collection and replaces it with the specified collection. 
    /// </summary> 
    public void ReplaceRange(IEnumerable<T> collection) 
    { 
     List<T> old = new List<T>(Items); 
     Items.Clear(); 
     foreach (var i in collection) Items.Add(i); 
     OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace)); 
    } 

    /// <summary> 
    /// Initializes a new instance of the System.Collections.ObjectModel.ObservableCollection(Of T) class. 
    /// </summary> 
    public ObservableCollection() 
     : base() { } 

    /// <summary> 
    /// Initializes a new instance of the System.Collections.ObjectModel.ObservableCollection(Of T) class that contains elements copied from the specified collection. 
    /// </summary> 
    /// <param name="collection">collection: The collection from which the elements are copied.</param> 
    /// <exception cref="System.ArgumentNullException">The collection parameter cannot be null.</exception> 
    public ObservableCollection(IEnumerable<T> collection) 
     : base(collection) { } 
} 
} 

this question

+0

그 경우에는 발생하지 않으려는 각 Add 문에 대해 CollectionChanged가 발생합니다. –

+0

@RaoBHavik, 내 대답, AddRange 메서드 호출의 CollectionChange를 한 번만 수정했습니다. –

1

표준에서 촬영 ObservableCollection<T> 지원하지 않습니다 이 시나리오. 필요한 로직을 가진 INotifyCollectionChanged 인터페이스를 구현하는 클래스를 만들 수 있습니다. 예를 들어, 모든 아이템을 다른 컬렉션으로 대체하는 단일 메소드와 같은 인터페이스를 만들 수 있습니다.

UI에 좋지 않을 수 있습니다. 예를 들어, 컬렉션 바인딩 요소가 선택되었거나 포커스가있는 경우 컬렉션을 완전히 다시 초기화하면이 상태가 손실됩니다. 귀하의 시나리오에 따라 다릅니다.

+0

솔루션에 내 컬렉션을 추가 할 수 없습니다. –

관련 문제