How to Raise an Event When a Property's Value Changes
You have a property named ImageFullPath1 that you want to raise an event for whenever its value changes. While you are aware of using the INotifyPropertyChanged interface, you prefer to utilize events for this purpose.
The INotifyPropertyChanged interface is, in fact, implemented with events. It has a single member, PropertyChanged, which is an event that can be subscribed to by consumers.
Safe Implementation:
The following code snippet demonstrates a safe implementation of the INotifyPropertyChanged interface with an additional event for a specific property (ImageFullPath):
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"); } } } protected void OnImageFullPathChanged(EventArgs e) { EventHandler handler = ImageFullPathChanged; if (handler != null) handler(this, e); } public event PropertyChangedEventHandler PropertyChanged; public event EventHandler ImageFullPathChanged; }
This implementation ensures the following:
CallerMemberAttribute in .NET 4.5:
For .NET 4.5 and above, the CallerMemberAttribute can be used to eliminate the hard-coded string for property names 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 a Custom Event When a Property Value Changes in C#?. For more information, please follow other related articles on the PHP Chinese website!