当 Publication 的 Read 属性发生变化时,如何更改 TotalPublicationsRead 的值?
public class Report
{
public ObservableCollection<Publication> Publications { get; set; }
public int TotalPublicationsRead { get; set; }
}
public class Publication : INotifyPropertyChanged
{
private bool read;
public bool Read
{
get { return this.read; }
set
{
if (this.read!= value)
{
this.publications = value;
OnPropertyChanged("Read");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private void OnPropertyChanged(string property)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
提前致谢。
请您参考如下方法:
如果您正在尝试按照我的想法行事,那么我会更改 TotalPublicationsRead 属性并忘记事件。在下面的代码中,我只计算列表中 Publication 已被 Read 的项目数。
按照您尝试执行此操作的方式,当 ObserableCollection 更改时,您必须有一个事件处理程序。然后,您必须将事件处理程序附加到 PropertyChanged 事件,这将增加或减少 TotalPublicationsRead 属性。我相信它会起作用,但它会复杂得多。
public class Report
{
public List<Publication> Publications { get; set; }
public int TotalPublicationsRead
{
get
{
return this.Publications.Count(p => p.Read);
}
}
}
public class Publication : INotifyPropertyChanged
{
private bool read;
public bool Read
{
get { return this.read; }
set { this.read = value; }
}
}
