Implementing INotifyPropertyChanged - does a better way exist?

前端 未结 30 3194
感情败类
感情败类 2020-11-21 05:23

Microsoft should have implemented something snappy for INotifyPropertyChanged, like in the automatic properties, just specify {get; set; notify;} I

30条回答
  •  萌比男神i
    2020-11-21 05:46

    I have written an article that helps with this (https://msdn.microsoft.com/magazine/mt736453). You can use the SolSoft.DataBinding NuGet package. Then you can write code like this:

    public class TestViewModel : IRaisePropertyChanged
    {
      public TestViewModel()
      {
        this.m_nameProperty = new NotifyProperty(this, nameof(Name), null);
      }
    
      private readonly NotifyProperty m_nameProperty;
      public string Name
      {
        get
        {
          return m_nameProperty.Value;
        }
        set
        {
          m_nameProperty.SetValue(value);
        }
      }
    
      // Plus implement IRaisePropertyChanged (or extend BaseViewModel)
    }
    

    Benefits:

    1. base class is optional
    2. no reflection on every 'set value'
    3. can have properties that depend on other properties, and they all automatically raise the appropriate events (article has an example of this)

提交回复
热议问题