Alex Smith
Alex Smith

Reputation: 468

Implementing (not handling) CollectionChanged event

I have created a class that extends the base class ListView.ColumnHeaderCollection (found in System.Windows.Forms) and I want to be able to receive a notification of when the collection is changed via INotifyCollectionChanged.

So far, I have:

public class MyCollection : ListView.ColumnHeaderCollection, INotifyCollectionChanged { ... }

In my initialization method, I am assigning the delegate my own method OnCollectionChanged().

UserSettings.Instance.Columns.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(OnCollectionChanged);

For those who are curious, my delegate looks like:

public void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    Settings_Save();
}

And so we arrive at my problem. I don't know how to implement the interface member required by INotifyCollectionChanged.

'_Namespace_.MyCollection' does not implement interface member 'System.Collections.Specialized.INotifyCollectionChanged.CollectionChanged'

Many thanks from this C# newbie!

Upvotes: 2

Views: 1579

Answers (1)

xenolightning
xenolightning

Reputation: 4230

As per INotifyCollectionChanged, it requires a public event member called CollectionChanged to be in the implementing class. I.e:

public class MyCollection : INotifyCollectionChanged
{
    public event NotifyCollectionChangedEventHandler CollectionChanged;
    // ...
}

EDIT: Overriding a non virtual property using the new keyword:

public class MyListView : ListView
{

    public new MyCollection Columns { get; set; }
    //...

}

However you have to be careful. If a reference type refers to ListView.Columns it will be a different collection than MyCollection.Columns and cause unexpected behaviour. When using new to override a base property you should set/get the base property, this preserves the integrity of the collections, I.e:

public class MyListView : ListView
{
    public new MyCollection Columns
    {
        get
        {
            return base.Columns as MyCollection;
        }
        set
        {
            base.Columns = value;
        }
    }
}

Upvotes: 4

Related Questions