我有一个班级
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中反映可观察集合中所有对象的实际总和。
谢谢!
答案 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"));
}
}