.NET(C#): 監控元素加入的ObservableCollection

來源:互聯網
上載者:User

簡單的改造一下,可以使ObservableCollection在任何有新成員加入的時候(注意包括已有成員被替換的情況),需要有一個事件進行通知,同時可以設定是否允許該新元素被加入。

 

原理很簡單,利用INotifyCollectionChanged介面的相關事件,來判斷新元素,然後出發自己的事件通知,最後根據事件EventArgs決定是否刪除這個新元素。

 

代碼:

//+ using System.Collections.ObjectModel;

//+ using System.Collections.Specialized;

class MyObserlist<T> : ObservableCollection<T>

{

    //INotifyCollectionChanged的CollectionChanged事件

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)

    {

        base.OnCollectionChanged(e);

 

        if (e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Replace)

        {

            var item = (T)e.NewItems[0];

            OnItemAdded(new ItemAddedEventArgs<T>(item), e.NewStartingIndex);

        }

    }

 

    //元素添加的事件

    public event EventHandler<ItemAddedEventArgs<T>> ItemAdded;

 

    protected virtual void OnItemAdded(ItemAddedEventArgs<T> e, int index)

    {

        var handler = this.ItemAdded;

        if (handler != null)

            handler(this, e);

 

        if (e.IsCancelled)

            RemoveAt(index);

    }

}

 

class ItemAddedEventArgs<T> : EventArgs

{

    //目標元素

    public T Item { get; private set; }

    //是否取消添加操作,預設當然是否

    public bool IsCancelled { get; set; }

 

    public ItemAddedEventArgs(T item)

    {

        Item = item;

    }

}

 

 

使用樣本,建立一個簡單的ObservableCollection,並且禁止所有偶數被添加進去:

static void Main(string[] args)

{

    var list = new List<int>();

    var collec = new MyObserlist<int>();

    collec.ItemAdded += collec_ItemAdded;

 

    //加入成功

    collec.Add(1);

    //禁止加入

    collec.Add(2);

    //將1改成4,加入失敗,此時collec中沒有任何元素

    collec[0] = 4;

 

    Console.WriteLine("Count: " + collec.Count);

 

}

 

//偶數不會被加入

static void collec_ItemAdded(object sender, ItemAddedEventArgs<int> e)

{

    if (e.Item % 2 == 0)

    {

        e.IsCancelled = true;

        Console.WriteLine("{0}被取消", e.Item);

    }

    else

        Console.WriteLine("{0}被加入", e.Item);

 

}

 

輸出:

1被加入

2被取消

4被取消

Count: 0

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.