簡體   English   中英

當可觀察集合中的任何項目發生更改時,更新當前的類屬性

[英]Update current class property when any item in observable collection changes

我上課了

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屬性經常更改。

SomeModel.SubModels可觀察集合中的任何項屬性SomeSubModel.Count被更改為通過綁定反映WPF UI中的實際SomeSubModel.Sum時,如何通知SomeSubModel.Sum被更改?

主要目標是在UI中反映可觀察集合中所有Count對象的實際總和。

謝謝!

在這種情況下,您應該觸發為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"));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM