假设我有一个简单的 Order 类,它有一个 TotalPrice 计算属性,可以绑定到 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; }
}
}
在影响 TotalPrice 计算的属性中调用 RaisePropertyChanged("TotalPrice") 是一种好习惯吗?刷新 TotalPrice 属性的最佳方法是什么?这样做的另一个版本当然是像这样更改属性
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"); 在其他属性中。请提出更好的解决方案
非常感谢