假设我有一个ReadOnlyObservableCollection
类型的集合,我想注册其受保护的事件CollectionChanged
......
我认为我可以用一种简单的方式克服,所以我创建了自己的类,它派生自ReadOnlyObservableCollection
,然后我订阅了这个事件并调用了我自己的事件:
public class MyCollection<T> : ReadOnlyObservableCollection<T>
{
public MyCollection(ObservableCollection<T> list) : base(list)
{
this.CollectionChanged += ThreadMessagesCollection_CollectionChanged;
this.PropertyChanged += ThreadMessagesCollection_PropertyChanged;
}
private void ThreadMessagesCollection_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
PropertyChanged(sender, e);
}
private void ThreadMessagesCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
OnCollectionChanged(sender, e);
}
public delegate void CollectionChagedDelegate(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e);
protected event PropertyChangedEventHandler PropertyChanged;
public event NotifyCollectionChangedEventHandler OnCollectionChanged;
}
但是,现在绑定不起作用。并没有发现异常...
知道我做错了什么,或者我怎么能克服它?
答案 0 :(得分:1)
您的event OnCollectionChanged
可能存在问题,因为OnCollectionChanged
已经是ReadOnlyObservableCollection
的虚拟方法。
我建议像这样试试:
public class MyCollection<T> : ReadOnlyObservableCollection<T>
{
public MyCollection([NotNull] ObservableCollection<T> list) : base(list) {}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
{
base.OnCollectionChanged(args);
OnMyCollectionChanged(args);
}
public event NotifyCollectionChangedEventHandler MyCollectionChanged;
protected virtual void OnMyCollectionChanged(NotifyCollectionChangedEventArgs e)
{
NotifyCollectionChangedEventHandler handler = MyCollectionChanged;
if (handler != null) handler(this, e);
}
}
您不需要定义自己的委托,因为已声明NotifyCollectionChangedEventHandler
已声明。