执行(不处理)CollectionChanged事件事件、CollectionChanged

2023-09-05 03:40:38 作者:回忆爱情里的折磨

我已经创建了一个扩展的基类 ListView.ColumnHeaderCollection (在 System.Windows.Forms的发现一类 ),我希望能够收到时,收集通过INotifyCollectionChanged改变的通知。

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.

到目前为止,我有:

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

在我的初始化方法,我分配委托我自己的方法 OnCollectionChanged()

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

因此​​,我们在我的问题到达。我不知道该如何落实 INotifyCollectionChanged 所需的接口成员。

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

从本C#新手非常感谢!

Many thanks from this C# newbie!

推荐答案

INotifyCollectionChanged ,它需要一个叫做公共事件成员 Col​​lectionChanged 是在实现类。即:

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

编辑:覆盖非虚拟财产使用的 关键字:

Overriding a non virtual property using the new keyword:

public class MyListView : ListView
{

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

}

然而,你必须要小心。如果引用类型是指 ListView.Columns 这将是一个不同的集合比 MyCollection.Columns 并导致意外的行为。当使用来覆盖你应该设置/获取基本属性基本属性,这preserves藏品的完整性,即:

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