我需要根據選定的價格和數量計算交易價值。如何才能C#MVVM計算總計
以下是我的視圖模型:
class ViewModel : ViewModelBase
{
public Trade Trade
{
get { return _trade; }
set { SetField(ref _trade, value,() => Trade); }
} private Trade _trade;
public decimal TradeValue
{
get { return Trade.Amount * Trade.Price; }
}
}
ViewModelBase繼承INotifyPropertyChanged的,幷包含SetField()
以下是貿易類:
public class Trade : INotifyPropertyChaged
{
public virtual Decimal Amount
{
get { return _amount; }
set { SetField(ref _amount, value,() => Amount); }
} private Decimal _amount;
public virtual Decimal Price
{
get { return _price; }
set { SetField(ref _price, value,() => Price); }
} private Decimal _price;
......
}
我知道由於設計我的TradeValue只計算一次(當它第一次請求時),並且當金額/價格變化時UI不會更新。達到這個目標的最好方法是什麼?
任何幫助非常感謝。
更新: INotifyPropertyChanged的實施:
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged<T>(Expression<Func<T>> selectorExpression)
{
if (selectorExpression == null)
throw new ArgumentNullException("selectorExpression");
var body = selectorExpression.Body as MemberExpression;
if (body == null)
throw new ArgumentException("The body must be a member expression");
OnPropertyChanged(body.Member.Name);
}
protected bool SetField<T>(ref T field, T value, Expression<Func<T>> selectorExpression)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(selectorExpression);
return true;
}
這兩個答案的工作,現在我不知道該選擇爲最佳答案是哪一個。盧克的答案似乎更好,因爲似乎有更少的代碼重複,但只是聽OnPropertyChanged事件似乎更輕量級。
你可以發佈SetField的代碼嗎? – luke 2010-06-09 17:41:28