簡單的改造一下,可以使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