使用System.Reactive在ObservableCollection中的项上观察PropertyChanged



我有:

public class Vm
{
    private ObservableCollection<Thing> _things;
    public ObservableCollection<Thing> Things
    {
        get { return _things ?? (_things = new ObservableCollection<Thing>()); }
    }
}

public class Thing :INotifyPropertyChanged
{
    private string _value;
    public string Value
    {
        get { return _value; }
        set
        {
            if (value == _value) return;
            _value = value;
            OnPropertyChanged();
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

我想观察ObservableCollection 中所有项目的PropertyChanges

rx适合这个吗?

在这种情况下,观察者是如何联系的?(我可以发布一些你尝试过的内容,但我认为不会增加太多)

Rx非常适合,我不会称之为重新发明轮子!

考虑一下将属性更改事件转换为可观察流的简单扩展方法:

public static class NotifyPropertyChangedExtensions
{
  public static IObservable<PropertyChangedEventArgs> WhenPropertyChanged(this NotifyPropertyChanged notifyPropertyChanged)
  {
      return Observable.FromEvent<PropertyChangedEventHandler, PropertyChangedEventArgs>(
        ev => notifyPropertyChanged.PropertyChanged += ev, 
        ev => notifyPropertyChanged.PropertyChanged -= ev);
  }    
}

在你的视图模型中,你只需合并所有可观察的属性变化流:

public class VM
{
  readonly SerialDisposable subscription;
  public VM()
  {
    subscription = new SerialDisposable();
    Things = new ObservableCollection<Thing>();
    Things.CollectionChanged += ThingsCollectionChanged;
  }
  void ThingsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  {
    subscription.Disposable = 
      Things.Select(t => t.WhenPropertyChanged())
            .Merge()
            .Subscribe(OnThingPropertyChanged);
  }
  void OnThingPropertyChanged(PropertyChangedEventArgs obj)
  {
    //ToDo!
  }
  public ObservableCollection<Thing> Things { get; private set; }
}

相关内容

  • 没有找到相关文章

最新更新