INotifyPropertyChanged的和计算的财产 [英] INotifyPropertyChanged and calculated property

查看:147
本文介绍了INotifyPropertyChanged的和计算的财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有简单的类订单,有计算的财产TotalPrice,它可以绑定到WPF UI

Suppose I have simple class Order, that have a TotalPrice calculated property, which can be bound to WPF UI

public class Order : INotifyPropertyChanged
{
  public decimal ItemPrice 
  { 
    get { return this.itemPrice; }
    set 
    {
       this.itemPrice = value;
       this.RaisePropertyChanged("ItemPrice");
       this.RaisePropertyChanged("TotalPrice");
    }
  }

  public int Quantity 
  { 
    get { return this.quantity; }
    set 
    {
       this.quantity= value;
       this.RaisePropertyChanged("Quantity");
       this.RaisePropertyChanged("TotalPrice");
    }
  }

  public decimal TotalPrice
  {
    get { return this.ItemPrice * this.Quantity; }    
  }
}



它是一个很好的做法,称之为RaisePropertyChanged( TotalPrice)的影响,以TotalPrice计算的属性?什么是刷新TotalPrice财产的最好方式?
另一个版本做当然,这是要改变这样的<​​/ p>

Is it a good practice to call RaisePropertyChanged("TotalPrice") in the properties that affect to TotalPrice calculation? What is the best way to refresh TotalPrice property? The other version to do this of course is to change property like this

public decimal TotalPrice
{
    get { return this.ItemPrice * this.Quantity; } 
    protected set 
    {
        if(value >= 0) 
            throw ArgumentException("set method can be used for refresh purpose only");

    }
}

和调用TotalPrice = -1,而不是this.RaisePropertyChanged(TotalPrice)的;在其它性质。请更好的建议的解决方案

and call TotalPrice = -1 instead of this.RaisePropertyChanged("TotalPrice"); in other properties. please suggest solutions better

非常感谢

推荐答案

它的优良请检查你是否应该从可能改变数值任何其他成员引发此事件为好,但只有这样做,如果你真正的变更的值。

It's fine to check to see if you should raise this event as well from any other member that may change the value, but only do so if you actually change the value.

您可以在一个方法封装这样的:

You could encapsulate this in a method:

private void CheckTotalPrice(decimal oldPrice)
{
    if(this.TotalPrice != oldPrice)
    {
         this.RaisePropertyChanged("TotalPrice");
    }
}



然后,你需要调用从您的其他变异成员

Then you need to call that from your other mutating members:

var oldPrice = this.TotalPrice;
// mutate object here...
this.CheckTotalPrice(oldPrice);

这篇关于INotifyPropertyChanged的和计算的财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆