要素の追加・削除だけであればObservableCollectionで良いのですが,さらにその要素の変更によって処理をさせたい!そう思った時のメモです.
以下のように,Rxを使ってコレクションの要素のPropertyChangedイベントをトリガーにして,さらに別プロパティのPropertyChangedイベントを発火させてみました.
// 要素
class Hoge : BindableBase
{
private bool isChecked;
public bool IsChecked
{
get
{
return this.isChecked;
}
set
{
this.isChecked = value;
this.OnPropertyChanged(() => IsChecked);
}
}
private int num;
public int Num
{
get
{
return this.num;
}
set
{
this.num= value;
this.OnPropertyChanged(() => Num);
}
}
}
// 別のクラス ViewModelとか
class Foo
{
// 監視するコレクション
public ObservableCollection<Hoge> HogeCollection
// HogeCollectionの内フラグがtrueの要素の値の合計値プロパティ
public int HogeSum
{
get
{
HogeCollection.Where(x => x.IsChecked).Sum(y => y.Num);
}
}
// HogeCollectionの値をセットする際
public void addItem(Hoge item)
{
// itemのPropertyChangedに対するハンドラの記述
Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
h => item.PropertyChanged += h,
h => item.PropertyChanged -= h)
.Subscribe(e =>
{
// 変更があったらHogeSumも変更する
this.OnPropertyChanged(() => this.HogeSum);
});
HogeCollection.add(item);
}
}