2011-09-06 45 views
1

在的ObservableCollection我怎麼能檢查CollectionChanged事件爲空或不是, 這個語句拋出語法錯誤如何檢查的ObservableCollection的「CollectionChanged」事件爲空或不是

if (studentList.CollectionChanged == null) 

的ErrorMessage:

事件'System.Collections.ObjectModel.ObservableCollection.CollectionChanged'只能出現在+ =的左側或 - =

示例代碼:

public class School 
    { 
     public School() 
     { 
      studentList = new ObservableCollection<Student>();    
      //only when studentList.CollectionChanged is empty i want 
      // to execute the below statement 
      studentList.CollectionChanged += Collection_CollectionChanged; 
     } 
     public ObservableCollection<Student> studentList { get; set; } 
    } 
+2

我不知道,你可以。爲什麼你想要,但是? – wilbur4321

+0

好問題,在上面的代碼中它只會被執行一次。但在我實際的情況下,當序列化和反序列化我鬆散collectionchanged事件,所以我實現我自己的ondeserialized方法,並附上resechanged編程。我需要檢查。 – user841683

回答

1

事件不是委託實例。

試試這個:

public class StudentList : ObservableCollection<Student> 
{ 
    public int CountOfHandlers { get; private set; } 

    public override event NotifyCollectionChangedEventHandler CollectionChanged 
    { 
     add {if (value != null) CountOfHandlers += value.GetInvocationList().Length;} 
     remove { if (value != null)CountOfHandlers -= value.GetInvocationList().Length; } 
    } 
} 

public class School 
{ 
    public School() 
    { 
     studentList = new StudentList(); 
     //only when studentList.CollectionChanged is empty i want 
     // to execute the below statement 
     if (studentList.CountOfHandlers == 0) 
     { 
      studentList.CollectionChanged += studentList_CollectionChanged; 
     } 
    } 

    public StudentList studentList { get; set; } 

    private void studentList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e){} 
} 

public class Student { } 
+0

謝謝,我以相同的方式處理它,你說略有不同的私人事件NotifyCollectionChangedEventHandler _collectionChanged; 公共覆蓋事件NotifyCollectionChangedEventHandler CollectionChanged { 添加 { 如果(_collectionChanged == NULL){ _collectionChanged + =值; } } 刪除 { _collectionChanged - = value; } } – user841683

4

您看不到事件是否具有從擁有該事件的類的外部附加的處理程序。你必須爲你想解決的問題找到一個不同的解決方案。

相關問題