Skip to content

Instantly share code, notes, and snippets.

@chitoku-k
Created December 31, 2014 15:53
Show Gist options
  • Save chitoku-k/07ebe9d012b932c62c9f to your computer and use it in GitHub Desktop.
Save chitoku-k/07ebe9d012b932c62c9f to your computer and use it in GitHub Desktop.
ObservableKeyedCollection
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
/// <summary>
/// キーが値に埋め込まれているコレクションを提供します。
/// </summary>
/// <typeparam name="TKey">コレクション内のキーの型。</typeparam>
/// <typeparam name="TItem">コレクション内の項目の型。</typeparam>
public class ObservableKeyedCollection<TKey, TItem> : KeyedCollection<TKey, TItem>, INotifyCollectionChanged
{
private Func<TItem, TKey> _selector;
/// <summary>
/// キーの抽出方法を指定して Soarer.Models.ObservableKeyedCollection&lt;TKey,TItem&gt; クラスの新しいインスタンスを初期化します。
/// </summary>
/// <param name="selector">項目からキーを取得するのに使われる関数。</param>
public ObservableKeyedCollection(Func<TItem, TKey> selector)
{
_selector = selector;
}
protected override TKey GetKeyForItem(TItem item)
{
return _selector(item);
}
protected override void ClearItems()
{
base.ClearItems();
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
protected override void InsertItem(int index, TItem item)
{
base.InsertItem(index, item);
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));
}
protected override void RemoveItem(int index)
{
var oldItem = this[index];
base.RemoveItem(index);
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, oldItem));
}
protected override void SetItem(int index, TItem item)
{
var oldItem = this[index];
base.SetItem(index, item);
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, item, oldItem, index));
}
/// <summary>
/// コレクションが変更された場合に発生します。
/// </summary>
public event NotifyCollectionChangedEventHandler CollectionChanged;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment