2010-11-27 53 views
2

我想爲基類上的屬性實現System.ComponentModel.INotifyPropertyChanged接口,但我不太確定如何將其掛鉤。WPF - 爲基類實現System.ComponentModel.INotifyPropertyChanged

這是我想獲得通知的屬性簽名:

public abstract bool HasChanged(); 

和我的基類代碼來處理的變化:

public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; 

private void OnPropertyChanged(String info) 
{ 
    PropertyChangedEventHandler handler = PropertyChanged; 
    if (handler != null) 
    { 
     handler(this, new PropertyChangedEventArgs(info)); 
    } 
} 

我該如何處理無需在每個子類中調用OnPropertyChanged(),就可以在基類中連接事件?

感謝,
桑尼

編輯: 好......所以我認爲,當HasChanged()的值發生變化,我應該叫OnPropertyChanged("HasChanged"),但我不知道怎麼去那進入基類。有任何想法嗎?

+0

一般來說,這是不可能的。 – Jon 2010-11-27 00:50:58

+0

此外,`HasChanged`在這裏是一種方法,而不是屬性。複製/粘貼錯誤? – Jon 2010-11-27 00:52:11

回答

2

這是你在追求什麼?

public abstract class ViewModelBase : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    //make it protected, so it is accessible from Child classes 
    protected void OnPropertyChanged(String info) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(info)); 
     } 
    } 

} 

注意OnPropertyChanged可訪問級別是受保護的。然後在你的具體類或子類,你這樣做:

public class PersonViewModel : ViewModelBase 
{ 

    public PersonViewModel(Person person) 
    { 
     this.person = person; 
    } 

    public string Name 
    { 
     get 
     { 
      return this.person.Name; 
     } 
     set 
     { 
      this.person.Name = value; 
      OnPropertyChanged("Name"); 
     } 
    } 
} 

編輯:再次讀取OP的問題後,我意識到,他並不想調用子類的OnPropertyChanged,所以我敢肯定這將工作:

public abstract class ViewModelBase : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    private bool hasChanged = false; 
    public bool HasChanged 
    { 
     get 
     { 
      return this.hasChanged; 
     } 
     set 
     { 
      this.hasChanged = value; 
      OnPropertyChanged("HasChanged"); 
     } 
    } 

    //make it protected, so it is accessible from Child classes 
    protected void OnPropertyChanged(String info) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(info)); 
     } 
    } 
} 

和子類:

public class PersonViewModel : ViewModelBase 
{ 
    public PersonViewModel() 
    { 
     base.HasChanged = true; 
    } 
}