Home >Backend Development >C++ >How to Raise Events for Property Value Changes in C#?
Raise Events for Property Value Changes
When working with properties, you may encounter the need to trigger an event whenever the property's value changes.
Question:
There's a property named ImageFullPath1 that requires an event to be fired whenever its value changes. Despite the existence of INotifyPropertyChanged, the requirement is to implement the solution using events.
Answer:
The INotifyPropertyChanged interface is indeed based on events. It has a single member, PropertyChanged, which is an event that allows consumers to subscribe to.
However, the suggested solution by Richard is not reliable. A safer implementation is:
public class MyClass : INotifyPropertyChanged { private string imageFullPath; protected void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, e); } protected void OnPropertyChanged(string propertyName) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } public string ImageFullPath { get { return imageFullPath; } set { if (value != imageFullPath) { imageFullPath = value; OnPropertyChanged("ImageFullPath"); } } } public event PropertyChangedEventHandler PropertyChanged; }
Features of this Implementation:
Additional Property-Specific Events:
If you also want to create an event for changes in a specific property, such as ImageFullPath, you can add:
protected void OnImageFullPathChanged(EventArgs e) { EventHandler handler = ImageFullPathChanged; if (handler != null) handler(this, e); } public event EventHandler ImageFullPathChanged;
Call OnImageFullPathChanged(EventArgs.Empty) after OnPropertyChanged("ImageFullPath").
CallerMemberAttribute in .Net 4.5:
In .Net 4.5 and above, the CallerMemberAttribute allows you to remove the hard-coded property name in the source code:
protected void OnPropertyChanged( [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "") { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } public string ImageFullPath { get { return imageFullPath; } set { if (value != imageFullPath) { imageFullPath = value; OnPropertyChanged(); } } }
The above is the detailed content of How to Raise Events for Property Value Changes in C#?. For more information, please follow other related articles on the PHP Chinese website!