【发布时间】:2011-01-15 04:57:27
【问题描述】:
假设我有一个简单的 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");在其他属性中。请提出更好的解决方案
非常感谢
【问题讨论】:
-
我认为
ItemPrice和Quantity不应该负责为TotalPrice提高PropertyChanged。这会起作用,但如果ItemPrice和Quantity在另一个班级怎么办 - 那么你将无法做到这一点,而必须以另一种方式做到这一点。我已经在另一个问题中回答了这个问题,即使属性在同一类或其他类中,答案也是相同的:stackoverflow.com/questions/43653750/…
标签: c# wpf inotifypropertychanged