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

时间:2009-11-10 12:17:28

标签: c# observablecollection propertychanged

如果发布的“读取”属性发生更改,如何更改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));
       }
   }           
}

提前致谢。

2 个答案:

答案 0 :(得分:4)

如果您正在尝试按照我的想法行事,那么我会更改TotalPublicationsRead属性并忘记事件。在下面的代码中,我只计算列表中PublicationRead的项目。

您尝试这样做的方式,您必须有一个事件处理程序,以便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; }
    }
}

答案 1 :(得分:0)