我首先在应用程序中使用EntityFramework数据库。我希望在我的ViewModel中的EntityCollection发生更改时能以某种方式收到通知。它不直接支持INotifyCollectionChanged (为什么?)而且我还没有成功地找到另一个解决方案。
这是我最新的尝试,它不起作用,因为ListChanged事件似乎没有被引发:
public class EntityCollectionObserver<T> : ObservableCollection<T>, INotifyCollectionChanged where T : class
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
public EntityCollectionObserver(EntityCollection<T> 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的变化吗?
丹
发布于 2011-04-13 21:36:53
虽然它在@Aron提到的简单用例中工作,但我无法让它在我的实际应用程序中正常工作。
事实证明,由于我不确定的原因,EntityCollection的内部IBindingList可能会以某种方式、在某处发生变化。我的观察者没有被调用的原因是因为他们正在寻找一个甚至不再被EntityCollection使用的旧IBindingList的变化。
以下是让它为我工作的技巧:
public class EntityCollectionObserver<T> : ObservableCollection<T> where T : class
{
private static List<Tuple<IBindingList, EntityCollection<T>, EntityCollectionObserver<T>>> InnerLists
= new List<Tuple<IBindingList, EntityCollection<T>, EntityCollectionObserver<T>>>();
public EntityCollectionObserver(EntityCollection<T> 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<IBindingList, EntityCollection<T>, EntityCollectionObserver<T>>(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));
}
}发布于 2013-04-17 17:42:18
您有没有尝试过处理在对相关端进行更改时发生的AssociationChanged。(继承自RelatedEnd。)
它给出了显示元素是被添加还是被删除的参数,并公开了该元素。
发布于 2011-04-06 04:14:00
您是如何映射事件的?粘贴你的代码并像下面这样映射事件对我来说很有效。
static void Main(string[] args)
{
EntityCollection<string> col = new EntityCollection<string>();
EntityCollectionObserver<string> colObserver = new EntityCollectionObserver<string>(col);
colObserver.CollectionChanged += colObserver_CollectionChanged;
col.Add("foo");
}
static void colObserver_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Console.WriteLine("Entity Collection Changed");
}https://stackoverflow.com/questions/5502698
复制相似问题