I'm designing a new class in C# which has a few properties. My users will want to know when each of them changes.
What's a better choice? INotifyPropertyChanged style of implementation, or just having separate events corresponding to my properties? Or both?
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 .
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.
The INotifyPropertyChanged changed interface is at the heart of XAML apps and has been a part of the . NET ecosystem since the early days of Windows Forms. The PropertyChanged event notifies the UI that a property in the binding source (usually the ViewModel) has changed. It allows the UI to update accordingly.
INotifyPropertyChanged is an interface member in System. ComponentModel Namespace. This interface is used to notify the Control that property value has changed. Sourcecode.zip.
Going forward, INotifyPropertyChanged
is the norm, and has much better support in WPF. I seem to recall that BindingList<T>
only respects INotifyPropertyChanged
(see HookPropertyChanged
and UnhookPropertyChanged
in reflector).
This is also more efficient, as the UI only needs one event hook, rather than one per event - and your class can be more efficient as it only needs a field for one handler (rather than either one per property, or the niggle of having to go via EventHandlerList
and a set of static keys)
The old style is mainly a hangover.
Implementing the INotifyPropertyChanged interface will give you the added benefit of having binding sources automatically listening to changes you make to your properties and updating the controls.
Try doing this. Create a class without the INotifyPropertyChanged interface and bind it to something. For instance you can bind one of its properties to the Text property of a TextBox. Add a button that will change, not the text of the TextBox, but the value of the respective property in the instance that is bound to the box. Run and click the button. The textbox will not be notified of the change. If you then implement the INotifyPropertyChanged in the class, have the property's setter notify of its change via the PropertyChanged even, after you repeat the experiment, you'll see the TextBox updating.
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