I have two Classes, one for ViewModel and one for Product.
The Product class has a property called Line Total, and the ViewModel Class has a property called Total Amount. The Product class is bound to a DataGrid and the user
inserts the quantity which subsequently and automatically updates the Line Total.
Here is the ViewModel class:
public class ViewModel : INotifyPropertyChanged
{
public ObservableCollection<Product> products { get; set; }// the children
private decimal _TotalAmount;
public decimal TotalAmount // <=== has to hold sum of [products.LineTotal]
{
get
{
return totalAmount;
}
set
{
if (value != _TotalAmount)
{
_TotalAmount = value;
onPropertyChanged(this, "TotalAmount");
}
}
}
Here is the Product class which is a child:
public class Product : INotifyPropertyChanged
{
private decimal _LineTotal;
public decimal LineTotal
{
get
{
return _LineTotal;
}
set
{
if (value != _LineTotal)
{
_LineTotal = value;
onPropertyChanged(this, "LineTotal");
}
}
}
}
My question is: How the TotalAmount can compute the sum of all Products [Line Total] ? How the child Products can notify the parent ViewModel to update the TotalAmount?
Something like:
foreach(var product in Products)
{
TotalAmount += product.LineTotal;
}
A way to achieve this, would be to recalculate the total amount every time a line total has been edited by the user and every time a product is added or removed from the
ObservableCollection.Since
ProductimplementsINotifyPropertyChangedand raises thePropertyChangedevent when a new line total is set, theViewModelcan handle that event and recalculate the total amount.ObservableCollectionhas aCollectionChangedevent that is raised when an item is added or removed from it, so theViewModelcan also handle that event and recalculate. (This part is not really necessary if products can only be changed and not added/removed by the user etc.).You can try out this small program to see how it could be done:
Code-behind
XAML: