4

我需要实现一个具有特殊功能的集合。另外,我想将这个集合绑定到一个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 更新

问题是什么?

4

1 回答 1

3

为了使您的集合被使用,您也应该实现 IEnumerable 和 IEnumerator。虽然,你可能最好子类化ObservableCollection<T>

于 2010-12-24T17:12:49.223 回答