我有一个模型SupplierInvoice如下:
public class SupplierInvoice
{
public bool Use { get; set; }
public ApInvoice Invoice { get; set; }
}
和一个ViewModel,其中包含这个模型的列表:
private List<SupplierInvoice> _SupplierInvoices;
public List<SupplierInvoice> SupplierInvoices
{
get
{
return this._SupplierInvoices;
}
set
{
if (this._SupplierInvoices != value)
{
this._SupplierInvoices = value;
this.RaisePropertyChanged("SupplierInvoices");
}
}
}
在这个ViewModel中我也有一个计算属性:
public decimal ApTotal
{
get
{
decimal total = 0;
if (this.SupplierInvoices != null)
{
foreach (SupplierInvoice invoice in this.SupplierInvoices)
{
if (invoice.Use)
{
total += invoice.Invoice.MthInvBal1;
}
}
}
return total;
}
}
此计算属性返回所有发票余额的总和(如果发票的Use属性为真)。在网格中的复选框中将Use属性选择为true。
现在…问题是:当SupplierInvoice模型的Use属性被更改时,我如何通知这个计算属性(ApTotal)的propertychanged ?
我想把你的List<TObject>
换成ObservableCollection<TObject>
就可以了。
从我记得的List
不是传播PropertyChangedEvent到UI线程。
这可能有点顽皮,但您总是可以这样做:
private List<SupplierInvoice> _SupplierInvoices;
public List<SupplierInvoice> SupplierInvoices
{
get
{
return this._SupplierInvoices;
}
set
{
if (this._SupplierInvoices != value)
{
this._SupplierInvoices = value;
this.RaisePropertyChanged("SupplierInvoices");
this.RaisePropertyChanged("ApTotal");
}
}
}
每当您有一个计算属性时,您只需要从计算中涉及的其他属性中引发INotifyPropertyChanged.PropertyChanged
事件。所以你的ApTotal
属性是从SupplierInvoices
属性中计算出来的,然后你可以从属性setter中通知接口:
public List<SupplierInvoice> SupplierInvoices
{
get
{
return this._SupplierInvoices;
}
set
{
if (this._SupplierInvoices != value)
{
this._SupplierInvoices = value;
this.RaisePropertyChanged("SupplierInvoices");
this.RaisePropertyChanged("ApTotal");
}
}
}