EntityFramework EntityCollection观察CollectionChanged

我首先在应用程序中使用EntityFramework数据库。 我想以某种方式通知我的ViewModel中的EntityCollection更改。 它不直接支持INotifyCollectionChanged (为什么?)并且我没有成功找到另一个解决方案。

这是我的最新尝试,由于ListChanged事件似乎没有被提升,因此无效:

 public class EntityCollectionObserver : ObservableCollection, INotifyCollectionChanged where T : class { public event NotifyCollectionChangedEventHandler CollectionChanged; public EntityCollectionObserver(EntityCollection entityCollection) : base(entityCollection) { IBindingList l = ((IBindingList)((IListSource)entityCollection).GetList()); l.ListChanged += new ListChangedEventHandler(OnInnerListChanged); } private void OnInnerListChanged(object sender, ListChangedEventArgs e) { if (CollectionChanged != null) CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } 

有没有人有任何想法我如何观察EntityCollection变化?

虽然它在@Aron注意到的简单用例中起作用,但我无法在实际应用程序中使其正常工作。

事实certificate,并且由于我不确定的原因 – 某种程度上某个地方的EntityCollection的内部IBindingList可以被更改。 我的观察者没有被调用的原因是因为他们正在寻找一个旧的IBindingList上的变化,甚至不再被EntityCollection使用。

这是让它为我工作的黑客:

 public class EntityCollectionObserver : ObservableCollection where T : class { private static List, EntityCollectionObserver>> InnerLists = new List, EntityCollectionObserver>>(); public EntityCollectionObserver(EntityCollection entityCollection) : base(entityCollection) { IBindingList l = ((IBindingList)((IListSource)entityCollection).GetList()); l.ListChanged += new ListChangedEventHandler(OnInnerListChanged); foreach (var x in InnerLists.Where(x => x.Item2 == entityCollection && x.Item1 != l)) { x.Item3.ObserveThisListAswell(x.Item1); } InnerLists.Add(new Tuple, EntityCollectionObserver>(l, entityCollection, this)); } private void ObserveThisListAswell(IBindingList l) { l.ListChanged += new ListChangedEventHandler(OnInnerListChanged); } private void OnInnerListChanged(object sender, ListChangedEventArgs e) { base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } 

您是否尝试过处理AssociationChanged在对相关结束进行更改时发生。 (inheritance自RelatedEnd。)

它给出了一个参数,显示是否添加或删除了一个元素,并公开了该元素。

你如何映射事件? 粘贴代码并映射事件如下所示对我有用。

 static void Main(string[] args) { EntityCollection col = new EntityCollection(); EntityCollectionObserver colObserver = new EntityCollectionObserver(col); colObserver.CollectionChanged += colObserver_CollectionChanged; col.Add("foo"); } static void colObserver_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { Console.WriteLine("Entity Collection Changed"); }