简体   繁体   中英

When should a “property changed” event be fired?

Is it appropriate to fire a "property changed" event when the actual value of a property does not change?

public int SomeProperty
{
    get { return this.mSomeProperty; }
    set
    {
        this.mSomeProperty = value;
        OnPropertyChanged(new PropertyChangedEventArgs("SomeProperty"));
    }
}

This will trigger the event even when the new value is identical to the old value. Is this bad practice?

Best practice is not to throw the event unless the value changed.

In your case the property is just an 'int', so it's just a simple equality check. If your property was an object in it's own right, there are more cases to consider

  1. You set the same instance again - No property change

  2. You set a different instance with different values - Throw a property change

  3. You set a different, but 'equal' instance ( ie, the two different objects have the same set of values and can be considered equivalent from your application's point of view ) - Throw a property change.

The last one is subject to some debate... has the property really changed when all of it's attributes are the same? If someone is using that property change to subscribe to changes in the subclass, they will need it to know to unsubscribe from the old class and subscribe to the new one. Therefore I err on the side of announcing the change.

No, don't fire the event unless the underlying value has actually changed.

Usually, you code the Setter such that it doesn't even bother trying to modify the underlying value unless it actually is different.

If you had an event called PropertySetterAccessed , then it would be appropriate to fire it when the value doesn't change. However, your event is called PropertyChanged , so it should only be fired when that actually happened. If your events/methods/classes etc don't do "what they say on the tin", you are creating a maintenance nightmare for someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM