4

I need to implement a collection with special capabilities. In addition, I want to bind this collection to a ListView, Therefore I ended up with the next code (I omitted some methods to make it shorter here in the forum):

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);
    }
}

I wanted to test it with a simple data class:

public class Person
{
    public string GivenName { get; set; }
    public string SurName { get; set; }
}

So I created an instance of myCollection class as follows:

myCollection<Person> _PersonCollection = new myCollection<Person>();
public myCollection<Person> PersonCollection
{ get { return _PersonCollection; } }

The problem is that the ListView does not update when the collection updates although I implemented the INotifyCollectionChanged interface.

I know that my binding is fine (in XAML) because when I use the ObservableCollecion class instead of myCollecion class like this:

 ObservableCollection<Person> _PersonCollection = new ObservableCollection<Person>();
    public ObservableCollection<Person> PersonCollection
    { get { return _PersonCollection; } }

the ListView updates

What is the problem?

Ahmad
  • 1,312
  • 11
  • 23
libi
  • 121
  • 1
  • 2
  • 3

1 Answers1

2

In order for your collection to be consumed, you should implement IEnumerable and IEnumerator too. Although, you're probably better off subclassing ObservableCollection<T>

devdigital
  • 33,472
  • 8
  • 93
  • 117
  • 1
    Better yet, implement `IList` – Gabe Dec 24 '10 at 17:25
  • Yes, or inherit from Collection. ObservableCollection also implements INotifyPropertyChanged. – devdigital Dec 24 '10 at 17:59
  • The thing is that ObservableCollection has many public methods that I don't want the users of my class to have access to, and if I subclass ObservableCollection I have no control of that. – libi Dec 25 '10 at 05:48
  • Such as? What about inheriting from ReadOnlyObservableCollection? http://msdn.microsoft.com/en-us/library/ms668620.aspx – devdigital Dec 25 '10 at 09:55
  • For example, I want the collection to behave in a simillar way to a queue (inserting items only to the end of the collection and deleting items only from the head of the collection). Therefore I want to forbid the use of: public void Insert(int index, T item); – libi Dec 25 '10 at 18:04