2010-11-27 57 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; 
    } 
}