輕量級MVVM框架Stylet介紹:(9)PropertyChangedBase


ropertyChangedBase 是實現 INotifyPropertyChanged 的類型的基類,它提供了用於引發 PropertyChanged 通知的方法。

引發通知

有多種方法可以引發 PropertyChanged 通知,具體取決於您要執行的操作。

最常見的情況是讓屬性在每次分配到時引發通知。PropertyChangedBase提供了一個很好的實用程序方法來提供幫助:SetAndNotify。通過引用,它需要一個字段和一個要分配給該字段的值。如果字段的值 != 該值,則進行分配,並引發屬性已更改通知。例如:

class MyClass : PropertyChangedBase
{
   private string _name;
   public string Name
   {
      get { return this._name; }
      set { SetAndNotify(ref this._name, value); }
   }

要連接到對象,必須放入視圖中:
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/>

如果要為當前屬性以外的屬性引發 PropertyChanged 通知,可以使用NotifyOfPropertyChange方法。如下所示:

class MyClass : PropertyChangedBase
{
   private string _firstName;
   public string FirstName
   {
      get { return _firstName; }
      private set
      {
         SetAndNotify(ref _firstName, value);

         // Preferred if you're using C# 6, as it provides compile-time safety
         this.NotifyOfPropertyChange(nameof(this.FullName));         
      }
   }

   private string _lastName;
   public string LastName
   {
      get { return _lastName; }
      private set
      {
         SetAndNotify(ref _lastName, value);

         // Preferred for C# 5 and below, as it provides compile-time safety
         this.NotifyOfPropertyChange(() => this.FullName);
      }
   }

   public string FullName
   {
      get { return FirstName + " " + LastName; }
   }
}

您還可以在構造函數中將內容連接在一起,如下所示:

class MyClass : PropertyChangedBase
{
   private string _firstName, _lastName;

   public MyClass()
   {
      this.Bind(s => s.FirstName, (o, e) => NotifyOfPropertyChange(nameof(FullName)));
      this.Bind(s => s.LastName, (o, e) => NotifyOfPropertyChange(nameof(FullName)));
   }

   public string FirstName
   {
      get { return _firstName; }
      private set { SetAndNotify(ref _firstName, value); }
   }

   public string LastName
   {
      get { return _lastName; }
      private set { SetAndNotify(ref _lastName, value); }
   }

   public string FullName
   {
      get { return FirstName + " " + LastName; }
   }
}

與 PropertyChanged.Fody 一起使用

PropertyChanged.Fody是一個很棒的包,它在編譯時注入代碼以自動為您的屬性引發PropertyChanged通知,從而允許您編寫非常簡潔的代碼。它還將找出屬性之間的依賴關系,並適當地引發通知,例如:

class MyClass : PropertyChangedBase
{
   public string FirstName { get; private set; }
   public string LastName { get; private set; }
   public string FullName { get { return String.Format("{0} {1}", this.FirstName, this.LastName); } }

   public void SomeMethod()
   {
      // PropertyChanged notifications are automatically raised for both FirstName and FullName
      this.FirstName = "Fred";
   }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM