c# - 使用 System.Reactive 观察 ObservableCollection 中项目的 PropertyChanged

标签 c# observablecollection system.reactive inotifypropertychanged

我有:

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);
  }    
}

在您的 View 模型中,您只需合并所有单独的可观察属性更改流:

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; }
}

关于c# - 使用 System.Reactive 观察 ObservableCollection 中项目的 PropertyChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17854345/

相关文章:

c# - 如何识别 List<T> 中对象的哪些属性发生了变化

绑定(bind)到 ObservableCollection 的 WPF TreeView 不更新根节点

c# - 热可观察和 IDisposable

c# - 只返回特定属性

c# - 如何在同一应用程序(Office 365)中同时配置表单例份验证和 Azure 身份验证?

c# - 对 XamDataGrid 使用复杂字段

c# - 异步流与响应式(Reactive)扩展相比如何?

.net - TPL 数据流和 Rx 组合示例

c# - 警告尝试构建 Service Fabric AspNetCore2 项目

javascript - 如何将动态值传递给字节数组