There is a property, it's named ImageFullPath1
public string ImageFullPath1 {get; set; }
I'm going fire an event whenever its value changed. I am aware of changing INotifyPropertyChanged
, but I want to do it with events.
There is a property, it's named ImageFullPath1
public string ImageFullPath1 {get; set; }
I'm going fire an event whenever its value changed. I am aware of changing INotifyPropertyChanged
, but I want to do it with events.
That said, I completely agree with Ryan. This scenario is precisely why INotifyPropertyChanged exists.
Raising an event when a property changes is precisely what INotifyPropertyChanged does. There's one required member to implement INotifyPropertyChanged and that is the PropertyChanged event. Anything you implemented yourself would probably be identical to that implementation, so there's no advantage to not using it.
The
INotifyPropertyChanged
interface is implemented with events. The interface has just one member,PropertyChanged
, which is an event that consumers can subscribe to.The version that Richard posted is not safe. Here is how to safely implement this interface:
Note that this does the following things:
Abstracts the property-change notification methods so you can easily apply this to other properties;
Makes a copy of the
PropertyChanged
delegate before attempting to invoke it (failing to do this will create a race condition).Correctly implements the
INotifyPropertyChanged
interface.If you want to additionally create a notification for a specific property being changed, you can add the following code:
Then add the line
OnImageFullPathChanged(EventArgs.Empty)
after the lineOnPropertyChanged("ImageFullPath")
.Since we have .Net 4.5 there exists the
CallerMemberAttribute
, which allows to get rid of the hard-coded string for the property name in the source code:If you change your property to use a backing field (instead of an automatic property), you can do the following:
I use largely the same patterns as Aaronaught, but if you have a lot of properties it could be nice to use a little generic method magic to make your code a little more DRY
Usually I also make the OnPropertyChanged method virtual to allow sub-classes to override it to catch property changes.