I need to calculate a trade value based on the selected price and quantity. How can
The following is my ViewModel:
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 inherits INotifyPropertyChanged and contains SetField()
The Following is the Trade class:
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;
......
}
I know due to the design my TradeValue only gets calculated once (when its first requested) and UI doesn’t get updated when amount/price changes. What is the best way of achieving this?
Any help greatly appreciated.
Update: INotifyPropertyChanged implementation:
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;
}
Both answers work, now I don’t know which one to select as best answer. Luke’s answer seems better as there seems to be less code repetition, although simply listening for the OnPropertyChanged event seems more lightweight.
Subscribe to PropertyChanged event on the Trade class in the set method for the Trade property in your VM class. In that eventhandler, post a propertychanged for property TradeValue.