简体   繁体   中英

how can i check ObservableCollection's “CollectionChanged” event is null or not

In ObservableCollection how can i check CollectionChanged event is null or not, This statement throws syntax error

 if (studentList.CollectionChanged == null)

ErrorMessage:

The event 'System.Collections.ObjectModel.ObservableCollection.CollectionChanged' can only appear on the left hand side of += or -=

Sample Code:

 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; }
  }

You cannot see whether or not an event has handlers attached from outside of the class that owns the event. You'll have to find a different solution to the problem you're trying to solve.

Events aren't delegate instances.

Try this:

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 { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM