INotifyPropertyChanged and consistency - when to raise PropertyChanged?

偶尔善良 提交于 2021-01-28 06:02:07

问题


I have a class that implements INotifyPropertyChanged. It has two properties whose values are related to each other, like, for example, a person's first and last name. If one property is updated, the other one needs to be updated as well. To communicate this I've made the setters private and added a public method to change both properties at the same time.

My question is if there's any rule or convention as to when to raise the PropertyChanged event? I'd like to delay raising the events for the two properties until the state is fully updated and the state of my object is consistent. However, I don't know if this would surprise, and thus cause trouble for the users of my code, or maybe confuse some library code somewhere.

Update

Another look at the documentation revealed the following:

The PropertyChanged event can indicate all properties on the object have changed by using either null or String.Empty as the property name in the PropertyChangedEventArgs.

This might solve my particular problem, although it does not seem like a universal solution if there are many properties on the object.

However, my question is still valid: Do we raise PropertyChanged right away or can/should we wait a little in certain cases.


回答1:


You should raise the PropertyChanged event when your object is in a consistent state. If you update two properties you should raise the events after both properties have been updated. "Waiting a little" does not really make sense - do you intend to use a timer to wait for some small amount of time (say 100 ms)?

Whatever is depending on your property change notifications wants to see a consistent object. E.g.:

public void SetFullName(String fullName) {
  // Naïve implementation.
  var names = fullName.Split(new[] { ' ' }, 2);
  FirstName = names[0];
  LastName = names[1];
  OnPropertyChanged("FirstName");
  OnPropertyChanged("LastName");
}


来源:https://stackoverflow.com/questions/22805169/inotifypropertychanged-and-consistency-when-to-raise-propertychanged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!