[英]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.