-
Notifications
You must be signed in to change notification settings - Fork 0
/
PropertyObserver.cs
76 lines (64 loc) · 2.76 KB
/
PropertyObserver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
#nullable enable
namespace PropertyObserving
{
public class PropertyObserver<TObject> where TObject : class, INotifyPropertyChanged, IDisposable
{
private TObject? _instance;
private Dictionary<string, (DelegateInvocationProxy Invocator, PropertyInfo Property)> _invocators = new Dictionary<string, (DelegateInvocationProxy, PropertyInfo)>();
public TObject? Instance
{
get => _instance;
set
{
if(ReferenceEquals(_instance, value))
return;
if(value != null)
{
value.PropertyChanged += InstancePropertyChanged;
}
};
}
private void InstancePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if(!_invocators.TryGetValue(e.PropertyName, out var invocatorDefinition))
return;
invocatorDefinition.Invocator.Invoke(sender, invocatorDefinition.Property.GetValue(sender));
}
public void ObserveProperty<TProperty>(Expression<Func<TObject, TProperty>> property, Action<TObject, TProperty> changedHandler)
{
if (!(property.Body is MemberExpression me && me.Member is PropertyInfo propertyInfo))
throw new ArgumentException("Invalid property shape", nameof(property));
if (changedHandler == null)
throw new ArgumentNullException(nameof(changedHandler));
DelegateInvocationProxy proxy;
if (_invocators.TryGetValue(propertyInfo.Name, out var invocatorInfo))
{
proxy = invocatorInfo.Invocator;
}
else
{
proxy = new DelegateInvocator<TObject, TProperty>();
_invocators.Add(propertyInfo.Name, (proxy, propertyInfo));
}
proxy.Add(changedHandler)
}
public void RemoveObserver<TProperty>(Expression<Func<TObject, TProperty>> property, Action<TObject, TProperty> changedHandler)
{
if (!(property.Body is MemberExpression me && me.Member is PropertyInfo propertyInfo))
throw new ArgumentException("Invalid property shape", nameof(property));
if (changedHandler == null)
throw new ArgumentNullException(nameof(changedHandler));
DelegateInvocationProxy proxy;
if (_invocators.TryGetValue(propertyInfo.Name, out var invocatorInfo))
{
proxy = invocatorInfo.Invocator;
}
_invocators[propertyInfo.Name].Invocator.Subtract(changedHandler);
}
}
}