INotifyPropertyChanged and propertyName

寵の児 提交于 2019-12-11 05:25:42

问题


I was never sure about the meaning of propertyName when implementing INotifyPropertyChanged. So generally you implement INotifyPropertyChanged as:

public class Data : INotifyPropertyChanged {
   public event PropertyChangedEventHandler PropertyChanged;

   private void NotifyPropertyChanged(string propertyName = "") {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

   private string itsID;
   public string ID { 
             get { return itsID; }
             set { 
                   if (itsID != value) {
                     itsID = value; 
                     NotifyPropertyChanged("ID");
                  }
   }
}

I was never sure about the propertyName argument to NotifyPropertyChanged(string propertyName).

  1. Can that be any arbitrary string (like "MyID" in the above example)?
  2. Or does .NET use Reflection to align it with a property in a class so it has to match the name of the property exactly?
  3. What if the propertyName doesn't match the name of the Property exactly, does .NET consider the entire object as changed?

回答1:


It's not .NET Framework itself per se, it's pretty much every PropertyChanged subscriber out there (some of which do indeed happen to be distributed as part of the framework) that assumes you use the interface as intended, by sending the property name. If you send a notification that the property MyID has changed, when another component is looking at the property ID, it will typically see the notification, compare the names, and conclude "this notification isn't for me".




回答2:


If you want to match the name of the property exactly, you can use the new C#6 feature called nameof. The nameof feature is answers all of your questions because we could say the main advantage of using nameof in one word is refactoring. And "refactoring" is the word that you are looking for based on your questions:

NotifyPropertyChanged(nameof(ID));

As an example renaming ID will change the name of the property too, or it will break compilation but the following doesn't:

NotifyPropertyChanged("ID")



回答3:


It has to match the name of the property exactly. On a side note, you should check that the value has actually changed before calling PropertyChanged since that is a relatively expensive call (WPF would not know the property has not changed). In VS2015, you can also use the nameof operator.



来源:https://stackoverflow.com/questions/40163085/inotifypropertychanged-and-propertyname

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