我已经为 RxCookBook 制作了一篇关于这个主题的文章,你可以在这里找到
https://github.com/LeeCampbell/RxCookbook/blob/master/Model/CollectionChange.md
关于 PropertyChange 通知的更多文章在这里https://github。 com/LeeCampbell/RxCookbook/blob/master/Model/PropertyChange.md
它通过汇总来自ObservableCollection<T>
. 通过使用 ,ObservableCollection<T>
您还可以在从集合中添加或删除项目时收到通知。
如果您不想使用ObservableCollection<T>
(即您只想跟踪集合的给定快照的属性),那么您将需要做其他事情。首先,我假设您有一个INoftifyPropertyChanged
toIObservable<T>
扩展方法,或者您将使用标准事件 toIObservable<T>
方法。
接下来,您可以将值列表投影到更改序列列表中,即IEnumerable<T>
to IEumerable<IObserable<T>>
。这使您可以使用Observable.Merge
将更改列表展平为单个更改流。
如果您不想使用上面的链接,这是一个示例:
void Main()
{
var myList = new List<MyThing>{
new MyThing{Name="Lee", Age=31},
new MyThing{Name="Dave", Age=37},
new MyThing{Name="Erik", Age=44},
new MyThing{Name="Bart", Age=24},
new MyThing{Name="James", Age=32},
};
var subscription = Observable.Merge(myList.Select(t=>t.OnAnyPropertyChanges()))
.Subscribe(x=>Console.WriteLine("{0} is {1}", x.Name, x.Age));
myList[0].Age = 33;
myList[3].Name = "Bob";
subscription.Dispose();
}
// Define other methods and classes here
public class MyThing : INotifyPropertyChanged
{
private string _name;
private int _age;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public int Age
{
get { return _age; }
set
{
_age = value;
OnPropertyChanged("Age");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public static class NotificationExtensions
{
/// <summary>
/// Returns an observable sequence of the source any time the <c>PropertyChanged</c> event is raised.
/// </summary>
/// <typeparam name="T">The type of the source object. Type must implement <seealso cref="INotifyPropertyChanged"/>.</typeparam>
/// <param name="source">The object to observe property changes on.</param>
/// <returns>Returns an observable sequence of the value of the source when ever the <c>PropertyChanged</c> event is raised.</returns>
public static IObservable<T> OnAnyPropertyChanges<T>(this T source)
where T : INotifyPropertyChanged
{
return Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
handler => handler.Invoke,
h => source.PropertyChanged += h,
h => source.PropertyChanged -= h)
.Select(_=>source);
}
}
这将输出:
Lee is 33
Bob is 24