c# – Nice way to add event on property change

Question:

There is a class that contains a property, and an event that should occur when this property changes:

class A
{
    public Value { get; set; }
    public event EventHandler ValueChanged;
}

There are two other classes that can change this property and should be notified if the property was not changed by them. Or rather, even this: they can be notified in any case, but it should be possible to find out who exactly initiated the change.

The problem is that in Value {set; } only a new value is passed, and you won't be able to find out the initiator. And the only way out that I see is to replace Value {get; set;} to set (newValue, initiator); get ();

Answer:

C # already has a mechanism for this kind of notification – INotifyPropertyChanged.

An example of the interaction of such a class and notifying all subscribers when any property of an object changes:

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;
}

It is also quite possible to do separate processing for any specific properties ( ImageFullPath in the case of this example):

protected void OnImageFullPathChanged(EventArgs e)
{
    EventHandler handler = ImageFullPathChanged;

    if (handler != null) handler(this, e);
}

public event EventHandler ImageFullPathChanged;
Scroll to Top