This repository has been archived by the owner on Aug 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
PropertyObserver
Mark Smith edited this page Aug 29, 2016
·
1 revision
The PropertyObserver
is a wrapper class that makes it easier to monitor INotifyPropertyChanged
events on child objects. It provides a type-safe way to register specific actions in response to specific property changes.
You pass the specific object that implements INotifyPropertyChanged
into the constructor and keep a reference to this object. You then register handlers for property changes using the RegisterHandler
method. When you are finished, you can Dispose
the property observer to remove all your handlers.
The object supports a fluent syntax where you can chain registrations together which makes it a single line of code to create and then wire up any property change notifications.
-
Source
: The object being monitored. It must implementINotifyPropertyChanged
.
-
RegisterHandler
: registers a delegate to be called when a specific property is changed. -
UnregisterHandler
: unregisters a specific property handler on the source object. -
Dispose
: removes all property notification handlers on the source object.
public class ParentViewModel : SimpleViewModel
{
ChildVM childVM;
PropertyObserver<ChildVM> childObserver;
// Create a nice title from the child.
public string Title => $"{childVM.Name} is {childVM.Age} years old.";
public ParentViewModel(ChildVM child)
{
childVM = child;
// Monitor INPC on the child
childObserver = new PropertyObserver<ChildVM>(child)
// Register two handlers - both invalidate our Title property.
.RegisterHandler(c => c.Name, RaisePropertyChanged(nameof(Title))
.RegisterHandler(c => c.Age, RaisePropertyChanged(nameof(Title));
}
...
}