使用System.Reactive观察ObservableCollection中的项目的PropertyChanged
我有:
public class Vm { private ObservableCollection _things; public ObservableCollection Things { get { return _things ?? (_things = new ObservableCollection()); } } }
和
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 WhenPropertyChanged(this NotifyPropertyChanged notifyPropertyChanged) { return Observable.FromEvent( ev => notifyPropertyChanged.PropertyChanged += ev, ev => notifyPropertyChanged.PropertyChanged -= ev); } }
在您的视图模型中,您只需合并所有单个可观察的属性更改流:
public class VM { readonly SerialDisposable subscription; public VM() { subscription = new SerialDisposable(); Things = new ObservableCollection(); 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 Things { get; private set; } }
- C#不一致的可访问性错误
- 在.NET中是否有相当于Mac OS X Document的模式表?
- 使用IIS Express但HttpContext.Current.User.Identity.Name为空,但不是Visual Studio Development Server
- 将var转换为c#中的List
- 在我的C#应用程序内部进行“ping”
- 为什么Gridview页脚添加了额外的列?
- 在Visual Studio for C#中从流畅的接口类intellisense隐藏GetHashCode / Equals / ToString?
- 在wpf c#应用程序中的其他另一个类中访问XAML的按钮和复选框的值
- 如何将以下JSON传递给C#补丁方法w或没有Javascript序列化程序