执行(不处理)CollectionChanged事件 [英] Implementing (not handling) CollectionChanged event

查看:852
本文介绍了执行(不处理)CollectionChanged事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个扩展的基类 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!

推荐答案

按<一个href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx"相对=nofollow> 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;
        }
    }
}

这篇关于执行(不处理)CollectionChanged事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆