Mikhail Sokolov
Mikhail Sokolov

Reputation: 556

How to fire event if model property changes

I developing application using backround processes and MVP pattern. Can I store states of processes (isCanceled, isStarted or isPaused) in ModelProcess (Model) like this:

public event EventHandler CancelChanged;
  bool isCanceled = false;
    public bool IsCanceled
    {
        get { return isCanceled; }
        set
        {
            isCanceled = value;
            if (isCanceled)
            {
                if (CancelChanged != null)
                {
                    CancelChanged(this, EventArgs.Empty);
                }
            }
        }
    }

Upvotes: 0

Views: 82

Answers (1)

Dennis Traub
Dennis Traub

Reputation: 51694

Your setter will only call CancelChanged if isCanceled is being set to true, no matter if it has been false before. The following code will check if there is an actual change of the value, wich makes it idempotent.

set
{
    if (value != isCanceled)
    {
        isCanceled = value;
        if (CancelChanged != null)
        {
            CancelChanged(this, EventArgs.Empty);
        }
    }
}

Upvotes: 1

Related Questions