2011-09-06 46 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

您看不到事件是否具有从拥有该事件的类的外部附加的处理程序。你必须为你想解决的问题找到一个不同的解决方案。

相关问题