I know that there are solutions out there for implementing INotifyPropertyChanged, but none of them are as simple as: reference this library, create/add this attribute, done (I'm thinking Aspect-Oriented Programming here). Does anyone know of a really simple way to do this? Bonus points if the solution is free.
Here are some relevant links (none of which provide a simple enough answer):
To implement INotifyPropertyChanged you need to declare the PropertyChanged event and create the OnPropertyChanged method. Then for each property you want change notifications for, you call OnPropertyChanged whenever the property is updated.
Remarks. The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .
The RaisePropertyChanging event is used to notify UI or bound elements that the data has changed. For example a TextBox needs to receive a notification when the underlying data changes, so that it can update the text you see in the UI.
Try this https://github.com/Fody/PropertyChanged
It will weave all properties of types that implement INotifyPropertyChanged and even handles dependencies.
Your Code
public class Person : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public string GivenNames { get; set; } public string FamilyName { get; set; } public string FullName { get { return string.Format("{0} {1}", GivenNames, FamilyName); } } }
What gets compiled
public class Person : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string givenNames; public string GivenNames { get { return givenNames; } set { if (value != givenNames) { givenNames = value; OnPropertyChanged("GivenNames"); OnPropertyChanged("FullName"); } } } private string familyName; public string FamilyName { get { return familyName; } set { if (value != familyName) { familyName = value; OnPropertyChanged("FamilyName"); OnPropertyChanged("FullName"); } } } public string FullName { get { return string.Format("{0} {1}", GivenNames, FamilyName); } } public void OnPropertyChanged(string propertyName) { var propertyChanged = PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }
Or you can use attributes for more fine grained control.
Here is an article showing how to handle this via PostSharp.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With