C# - 如何根据另一个属性 (ObservableCollection) 的更改来更改属性的值?

emp*_*mpo 4 c# observablecollection propertychanged

当发布的 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));
       }
   }           
}
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Jon*_*ell 6

如果你想按照我的想法去做,那么我会改变属性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; }
    }
}
Run Code Online (Sandbox Code Playgroud)