通过NotifyCollectionChangedEventArgs或sender获取实例的ObservableCollection

时间:2016-12-05 20:39:08

标签: c# wpf .net-4.0

我有一个House-Objects列表。这些继承了ObservableCollections of Persons

public class House{
    public ObservableCollection<Person> Residents = new ObservableCollection<Person>();
    ...
}

在任何课程中我都添加了Residents-Handler

List<House> Village = new List<House>(); 
foreach (House h in Village) {
    h.Residents.CollectionChanged += OnResidents_Changed;
}

处理:

private void OnResidents_Changed(object sender, NotifyCollectionChangedEventArgs e) {
    if (e.NewItems!= null) {
        foreach(Person p in e.NewItems){
            //In which house did he go?
            e.GetSourceCollection() //<- how to solve
        }
    }
}

这个人也应该同时在一个以上的房子里。我没有可能改变人的属性。

THX!

1 个答案:

答案 0 :(得分:2)

sender参数包含ObservableCollection实例:

private void OnResidents_Changed(object sender, NotifyCollectionChangedEventArgs e)
{
    var collection = (ObservableCollection<Person>)sender;

    ...
}

作为一个注释,您应该将集合声明为(只读)属性而不是字段,以使其可以访问WPF数据:

public class House
{
    public ObservableCollection<Person> Residents { get; }
        = new ObservableCollection<Person>();

    ...
}