INotifyPropertyChanged 与列表

INotifyPropertyChanged with a List

将 INotifyPropertyChanged 与列表一起使用的正确方法是什么?

我有一个 CertInfo class,它是 class 个认证:

    namespace ResumeApp
{
    public class CertInfo
    {
        public DateTime AcquiredDate { get; set; }
        public String Certification { get; set; }
        public bool Enabled { get; set; }
        public int UserId { get; set; }

        public CertInfo()
        {}

        public CertInfo(DateTime acquiredDate, String cert, bool enabled, int userId)
        {
            this.AcquiredDate = acquiredDate;
            this.Certification = cert;
            this.Enabled = enabled;
            this.UserId = userId;
        }
    }
}

我有一份简历 class 是 INotifyPropertyChanged。我不确定如何使用带有列表的通知。这是我的简历 class:

    namespace ResumeApp
{
    public class Resume : INotifyPropertyChanged
    {
        private PersonalInfo personal;
        private int userId;
        private ObservableCollection<CertInfo> certList;

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public Resume()
        {
            personal = new PersonalInfo();
            userId = 0;
            certList = new ObservableCollection<CertInfo>();
        }

        public PersonalInfo Personal
        {
            get { return personal; }
            set
            {
                if (value != null)
                {
                    personal = value;
                    OnPropertyChanged("Personal");
                }
            }
        }

        public int UserId
        {
            get { return userId; }
            set
            {
                if (value != 0)
                {
                    userId = value;
                    OnPropertyChanged("UserId");
                }
            }
        }

        public ObservableCollection<CertInfo> CertList
        {
            get { return certList; }
            set
            {
                if(value != null)
                {
                    certList = value;
                    OnPropertyChanged("CertList");
                }
            }
        }
    }
}

对吗?

谢谢

如果您打算在 Resume 的实例中更改 ObservableCollection<CertInfo> 的实际实例,那将是正确的。

然而,在大多数情况下,用只获取 属性 声明这种类型的关联是绝对足够的,因为集合本身真的永远不会改变,只有它的元素(添加/删除)。ObservableCollection<T> 本身实现 INotifyCollectionChanged,通知 UI 这些修改。

您可以将 CertList-属性 剥离为以下声明:

public ObservableCollection<CertInfo> CertList { get; } = new ObservableCollection<CertInfo>();

要使用给定集合预初始化实例,我建议使用以下构造函数:

public Resume(ObservableCollection<CertInfo> certList) {
  //null-checks ommited
  CertList = certlist;
  //more initialization
  userId = 0;

}
public Resume(IEnumerable<CertInfo> certList) : this (new ObservableCollection(certlist) {

}
public Resume() : this(new ObservableCollection<CertInfo>()) {
}