使用System.Reactive在ObservableCollection中的项目上观察PropertyChanged [英] Observe PropertyChanged on items in an ObservableCollection using System.Reactive
本文介绍了使用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
I want to observe PropertyChanges on all items in the ObservableCollection
rx适合吗?
在这种情况下,观察者如何连线? (我可以发布一些您尝试过的内容,但我认为这不会增加太多内容)
How is the observer wired up in this case? (I could post some what-have-you-tried but I don't think it will add much)
推荐答案
Rx是完美的选择,我不会称之为重新发明轮子!
Rx is a perfect fit and I wouldn't call it reinventing the wheel!
考虑以下简单的扩展方法,即可将属性更改的事件转换为可观察的流:
Consider this simple extension method for converting property changed events to observable streams:
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);
}
}
在视图模型中,您只需合并所有单个可观察的属性更改流:
In your view model you simply merge all individual obserable property change stream:
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; }
}
这篇关于使用System.Reactive在ObservableCollection中的项目上观察PropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文