@@ -13,15 +13,11 @@ public static IDisposable WatchProperty<TOwner, TProperty>(
13
13
this TOwner owner ,
14
14
Expression < Func < TOwner , TProperty > > propertyExpression ,
15
15
Action callback ,
16
- bool watchInitialValue = true
16
+ bool watchInitialValue = false
17
17
)
18
18
where TOwner : INotifyPropertyChanged
19
19
{
20
- var memberExpression =
21
- propertyExpression . Body as MemberExpression
22
- // Property value might be boxed inside a conversion expression, if the types don't match
23
- ?? ( propertyExpression . Body as UnaryExpression ) ? . Operand as MemberExpression ;
24
-
20
+ var memberExpression = propertyExpression . Body as MemberExpression ;
25
21
if ( memberExpression ? . Member is not PropertyInfo property )
26
22
throw new ArgumentException ( "Provided expression must reference a property." ) ;
27
23
@@ -48,21 +44,51 @@ public static IDisposable WatchProperties<TOwner>(
48
44
this TOwner owner ,
49
45
IReadOnlyList < Expression < Func < TOwner , object ? > > > propertyExpressions ,
50
46
Action callback ,
51
- bool watchInitialValue = true
47
+ bool watchInitialValue = false
52
48
)
53
49
where TOwner : INotifyPropertyChanged
54
50
{
55
- var watchers = propertyExpressions
56
- . Select ( x => WatchProperty ( owner , x , callback , watchInitialValue ) )
51
+ var properties = propertyExpressions
52
+ . Select ( expression =>
53
+ {
54
+ var memberExpression =
55
+ expression . Body as MemberExpression
56
+ // Because the expression is typed to return an object, the compiler will
57
+ // implicitly wrap it in a conversion unary expression if it's of any other type.
58
+ ?? ( expression . Body as UnaryExpression ) ? . Operand as MemberExpression ;
59
+
60
+ if ( memberExpression ? . Member is not PropertyInfo property )
61
+ throw new ArgumentException ( "Provided expression must reference a property." ) ;
62
+
63
+ return property ;
64
+ } )
57
65
. ToArray ( ) ;
58
66
59
- return Disposable . Create ( ( ) => watchers . DisposeAll ( ) ) ;
67
+ void OnPropertyChanged ( object ? sender , PropertyChangedEventArgs args )
68
+ {
69
+ if (
70
+ string . IsNullOrWhiteSpace ( args . PropertyName )
71
+ || properties . Any ( p =>
72
+ string . Equals ( args . PropertyName , p . Name , StringComparison . Ordinal )
73
+ )
74
+ )
75
+ {
76
+ callback ( ) ;
77
+ }
78
+ }
79
+
80
+ owner . PropertyChanged += OnPropertyChanged ;
81
+
82
+ if ( watchInitialValue )
83
+ callback ( ) ;
84
+
85
+ return Disposable . Create ( ( ) => owner . PropertyChanged -= OnPropertyChanged ) ;
60
86
}
61
87
62
88
public static IDisposable WatchAllProperties < TOwner > (
63
89
this TOwner owner ,
64
90
Action callback ,
65
- bool watchInitialValues = true
91
+ bool watchInitialValues = false
66
92
)
67
93
where TOwner : INotifyPropertyChanged
68
94
{
0 commit comments