formicini
formicini

Reputation: 348

Handle Event before a Property Changes

Is there an event handler that allows me to do something before a class' variable change value ? I only know about INotifyPropertyChanged/OnPropertyChanged, but that is after the value has been modified.

Upvotes: 0

Views: 117

Answers (2)

Florian Schmidinger
Florian Schmidinger

Reputation: 4692

Example for INotifyPropertyChanging:

public class AClass : INotifyPropertyChanging
{

    private int aField;

    public int AProperty
    {
        get { return aField; }
        set 
        {
            OnPropertyChanging("AProperty");
            aField = value; 
        }
    }


    private void OnPropertyChanging(string propertyName) 
    {
        PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
    }

    public event PropertyChangingEventHandler PropertyChanging = delegate { };
}

Upvotes: 1

aush
aush

Reputation: 2108

public class MyClass
{
    public event Action NotifyBeforeChanged;

    private int _value;
    public int Value
    {
        get
        {
            return _value;
        }
        set
        {
            NotifyBeforeChanged();
            _value = value;
        }
    }
}

Upvotes: 1

Related Questions