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 { }
精彩评论