-2

我有一堂动物课。在类 Animal 中,我有一个名为 Dogs 的另一个类的列表。

class Animal
{
  List<Dog> Dogs;
  int CountNeutedDogs;


  class Dog
  {
     // some properties
     boolean neuted;
   }
 }

该列表可能在任何时候都包含大约 500 只狗。我想要一个事件,以便如果狗中的 neuted 属性的值发生变化,则会通知和更新 CountNeutedDogs。我该怎么做呢?

编辑

我应该解释一下 Dogs 列表绑定到数据网格。用户可以将 neuted 属性从 false 更改为 true,反之亦然。我有一个获取和设置的属性。所以 neuted 值可能会改变,我需要更新 CountNeutedDogs 值,这就是为什么我考虑使用事件但不知道该怎么做。

4

2 回答 2

4

如果您将 CountNeutedDogs 设为这样的属性,则它始终是正确的,无需更新事件:

int CountNeutedDogs
{
    get
    {
        return this.Dogs.Where(d => d.neuted).Count();
    }
}
于 2013-09-30T09:11:01.830 回答
2

这是评论的后续行动:

我举了一个例子,(未经测试!!)如何通过实现ObservableCollection和来解决这个问题INotifyPropertyChanged

public class Dog : INotifyPropertyChanged
{
    private bool _isNeutered;

    public bool IsNeutered 
    {
        get { return _isNeutered; }
        set 
        {
            if (_isNeutered != value)
            {
                _isNeutered = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("IsNeutered"));
            }
        } 
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class Animals : INotifyPropertyChanged
{
    private ObservableCollection<Dog> _dogs = new ObservableCollection<Dog>();

    public Animals()
    {
        _dogs.CollectionChanged += Dogs_CollectionChanged;
    }


    // NOTE, I haven't checked this!! But I think it should be something like this:
    private void Dogs_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                foreach (INotifyPropertyChanged item in e.NewItems.OfType<INotifyPropertyChanged>())
                    item.PropertyChanged += Item_PropertyChanged;
                break;

            case NotifyCollectionChangedAction.Reset:
            case NotifyCollectionChangedAction.Remove:
                foreach (INotifyPropertyChanged item in e.OldItems.OfType<INotifyPropertyChanged>())
                    item.PropertyChanged -= Item_PropertyChanged;
                break;
        }

        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("NeuteredDogsCount"));
    }

    private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("NeuteredDogsCount"));
    }

    public IEnumerable<Dog> Dogs 
    { 
        get { return _dogs; } 
    }

    public int NeuteredDogsCount
    {
        get
        {
            return Dogs.Where(dog => dog.IsNeutered).Count();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

所以当集合发生变化时,NeuteredDogsCount会发送属性的通知。这样,有界控件将重新评估该NeuteredDogsCount属性。

而不是“正常”属性,IsNeutered可以更改为DependencyProperty.

于 2013-09-30T09:31:39.490 回答