当可观察集合中的任何项目发生更改时,更新当前的类属性

时间:2014-05-23 22:17:04

标签: c# wpf

我有一个班级

public class SomeModel : INotifyPropertyChanged {

  public ObservableCollection<SomeSubModel> SubModels {get; set;}

  public int Sum { get { return SubModels.Sum(x=> x.Count) }}

  private string _url;
  public string Url
  {
    get { return _url; }
    set
    {
        _url = value;
        OnPropertyChanged();
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  [NotifyPropertyChangedInvocator]
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  {
    var handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
  }

}

public class SomeSubModel : INotifyPropertyChanged {

  private string _count;
  public string Count
  {
    get { return _count; }
    set
    {
        _count = value;
        OnPropertyChanged();
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  [NotifyPropertyChangedInvocator]
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  {
    var handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
  }

}

我将在WPF UI中使用绑定到SomeSubModel.Sum

SomeSubModel.Count属性经常更改。

SomeSubModel.Sum可观察集合中的任何项目的属性SomeSubModel.Count更改为通过绑定反映WPF UI中的实际SomeModel.SubModels时,如何通知SomeSubModel.Sum已更改?

主要目标是在UI中反映可观察集合中所有对象的实际总和。

谢谢!

1 个答案:

答案 0 :(得分:2)

在这种情况下,您应该触发为Sum属性更改的notify属性:

private string _count;
public string Count
{
    get { return _count; }
    set
    {
        _count = value;
        OnPropertyChanged();
        var handler = PropertyChanged;
        if (handler != null) 
            handler(this, new PropertyChangedEventArgs("Sum"));
    }
}