假设我有
public class Parent
{
private IList<Child> _children;
public void AddChild(Child child)
{
_children.Add(child);
child.OnSmthChanged += ParentSmthChangedHandler;
}
public void RemoveChild(Child child)
{
_children.Remove(child);
child.OnSmthChanged -= ParentSmthChangedHandler;
}
}
public class Child
{
public event EventHandler OnSmthChanged;
}
当从数据库加载_children时,如何让NHibernate恢复事件?请注意:
所以,我考虑拦截NHibernate做_children的加载,并递归地添加事件。两个问题:
答案 0 :(得分:1)
你可以告诉nhibernate为_children字段使用observable collection:
<bag collection-type="uNhAddIns.WPF.Collections.Types.ObservableBagType`1[Your.Namespace.Child
, Your.Assembly.Name], uNhAddIns.WPF" ... />
然后:
public Parent()
{
(_children as INotifyCollectionChanged).CollectionChanged += DoSomething;
}
public void DoSomething(object sender, NotifyCollectionChangedEventArgs e)
{
if(e.Action == NotifyCollectionChangedAction.Add)
foreach(var child in e.NewItems.Cast<Child>())
child.OnSmthChanged += ParentSmthChangedHandler;
if(e.Action == NotifyCollectionChangedAction.Remove)
foreach(var child in e.OldItems.Cast<Child>())
child.OnSmthChanged -= ParentSmthChangedHandler;
}
你可以找到here。