代码之家  ›  专栏  ›  技术社区  ›  Sonny Boy

WPF-为基类实现System.ComponentModel.INotifyPropertyChanged

  •  2
  • Sonny Boy  · 技术社区  · 14 年前

    这是我要获取通知的属性的签名:

    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") ,但我不知道如何把它放到基类中。有什么想法吗?

    1 回复  |  直到 14 年前
        1
  •  2
  •   VoodooChild    14 年前

    这就是你要找的吗?

    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");
            }
        }
    }
    

    编辑:再次阅读操作题后,我意识到他不想打电话给 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;
        }
    }