列表中的项目更改时,计算属性的NotifyPropertyChanged

时间:2014-06-25 14:03:05

标签: c# wpf mvvm inotifypropertychanged

我有一个型号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;
    }
}

此计算属性返回所有发票余额的总和(如果发票的“使用”属性为true)。在视图中选中Use属性为true,并在网格中使用复选框。

现在......问题是:当SupplierInvoice模型的Use属性发生变化时,如何NotifyPropertyChanged这个计算属性(ApTotal)?

3 个答案:

答案 0 :(得分:0)

我认为将List<TObject>替换为ObservableCollection<TObject>即可。

据我所知,List没有将PropertyChangedEvent传播到UI线程。

答案 1 :(得分:0)

这可能有点顽皮,但你总能做到这一点:

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");
        }
    }
}

答案 2 :(得分:0)

每当你有一个计算属性时,你只需要从计算中涉及的其他属性中引发INotifyPropertyChanged.PropertyChanged事件。因此,ApTotal属性仅从SupplierInvoices属性计算,那么您只需从该属性设置器通知接口:

public List<SupplierInvoice> SupplierInvoices
{
    get
    {
        return this._SupplierInvoices;
    }
    set
    {
        if (this._SupplierInvoices != value)
        {
            this._SupplierInvoices = value;
            this.RaisePropertyChanged("SupplierInvoices");
            this.RaisePropertyChanged("ApTotal");
        }
    }
}