我需要实现一个具有特殊功能的集合。此外,我想将这个集合绑定到一个ListView,因此我最后使用了下面的代码(我在论坛中省略了一些方法以使其更简短):
public class myCollection<T> : INotifyCollectionChanged
{
private Collection<T> collection = new Collection<T>();
public event NotifyCollectionChangedEventHandler CollectionChanged;
public void Add(T item)
{
collection.Insert(collection.Count, item);
OnCollectionChange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
protected virtual void OnCollectionChange(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
CollectionChanged(this, e);
}
}我想用一个简单的数据类来测试它:
public class Person
{
public string GivenName { get; set; }
public string SurName { get; set; }
}所以我创建了一个myCollection类的实例,如下所示:
myCollection<Person> _PersonCollection = new myCollection<Person>();
public myCollection<Person> PersonCollection
{ get { return _PersonCollection; } }问题是,尽管我实现了INotifyCollectionChanged接口,但当集合更新时,ListView不会更新。
我知道我的绑定很好(在XAML中),因为当我使用ObservableCollecion类而不是myCollecion类时,如下所示:
ObservableCollection<Person> _PersonCollection = new ObservableCollection<Person>();
public ObservableCollection<Person> PersonCollection
{ get { return _PersonCollection; } }ListView更新
有什么问题吗?
发布于 2010-12-25 01:12:49
为了让你的集合被消费,你也应该实现IEnumerable和IEnumerator。不过,您最好将ObservableCollection<T>子类化
https://stackoverflow.com/questions/4527391
复制相似问题