我如何检查ObservableCollection的“CollectionChanged”事件是否为null

时间:2011-09-06 23:20:16

标签: c#

在ObservableCollection中,我如何检查CollectionChanged事件是否为null, 此语句抛出语法错误

 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 个答案:

答案 0 :(得分:4)

您无法查看某个事件是否具有从拥有该事件的类外部附加的处理程序。您必须找到解决您尝试解决的问题的不同解决方案。

答案 1 :(得分: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 { }