using StatefulModel.EventListeners; using System.ComponentModel; // ReSharper disable once CheckNamespace namespace System.Application { public static class PropertyChangedExtensions { /// /// 订阅事件 /// public static IDisposable Subscribe(this INotifyPropertyChanged source, PropertyChangedEventHandler handler) { return new PropertyChangedEventListener(source, handler); } /// /// 订阅事件 /// /// イベント ソース。 /// イベント発生時に、 を受け取って実行されるメソッド。 public static IDisposable Subscribe(this INotifyPropertyChanged source, Action action) { return new PropertyChangedEventListener(source, (sender, args) => action(args.PropertyName)); } /// /// 与指定的属性名称一起执行 订阅事件 /// /// 事件源 /// 订阅事件的属性的名称 /// 事件发生时执行的方法 /// 在调用此方法时 如果只运行一次,则为true,否则为false,默认值是true。 public static ListenerWrapper Subscribe(this INotifyPropertyChanged source, string propertyName, Action action, bool immediately = true) { return new ListenerWrapper(source).Subscribe(propertyName, action, immediately); } public class ListenerWrapper : IDisposable { //用于一个事件源 //当要订阅多个属性更改通知时 // EventSource // <-INotifyPropertyChanged对象 // .Subscribe(nameof(Property1),()=> {...}) // .Subscribe(nameof(Property2),()=> {...}) // .Subscribe(nameof(Property3),()=> {...}) // .AddTo(this); //仅出于编写目的而准备 private readonly PropertyChangedEventListener _listener; internal ListenerWrapper(INotifyPropertyChanged source) { this._listener = new PropertyChangedEventListener(source); } /// /// 与指定的属性名称一起执行 订阅事件 /// /// 订阅事件的属性的名称 /// 事件发生时执行的方法。 /// 在调用此方法时 如果只运行一次,则为true,否则为false,默认值是true。 public ListenerWrapper Subscribe(string propertyName, Action action, bool immediately = true) { if (immediately) action(); this._listener.Add(propertyName, (sender, args) => action()); return this; } void IDisposable.Dispose() => this._listener.Dispose(); } } }