LoginSignup
15
14

More than 5 years have passed since last update.

Collectionの要素の変更検知の仕方

Posted at

要素の追加・削除だけであれば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);
  }
}
15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14