Database Reference
In-Depth Information
{
var item = e.Element as CartItem;
item.PropertyChanged += (ps, pe) =>
{
if (pe.PropertyName == "Quantity")
{
this.CartTotal =
this.CartItems.Sum(t => t.Price * t.Quantity);
Console.WriteLine("Qty changed, total = {0}",
this.CartTotal.ToString("C"));
}
};
}
this.CartTotal = this.CartItems.Sum(t => t.Price * t.Quantity);
Console.WriteLine("New total = {0}",
this.CartTotal.ToString("C"));
};
}
}
Following is the output from the code in Listing 12-4:
New total = $59.85
New total = $119.80
New total = $129.70
Qty changed, total = $89.80
Cart Total = $89.80
New total = $89.80
SKU = AMM-223, Qty = 1, Unit Price = $19.95
SKU = CAMP-12, Qty = 1, Unit Price = $59.95
SKU = 29292, Qty = 2, Unit Price = $4.95
How It Works
To keep the CartTotal property in sync with the items in the CartItems collection, we need to wire in a handler for the
AssociationChanged event on the CartItems collection. We do this in the constructor for the Cart entity.
The event handler is a little complicated because we have to consider two cases. In the first case, we're simply
adding or removing an item from the cart. Here we just recalculate the total by iterating through the collection and
summing the price for each item multiplied by the quantity of the item. To get this sum, we use the Sum() method and
pass in a lambda expression that multiplies the price and quantity.
In the second case, the entity collection remains the same, but one of the items has its quantity changed. This
also affects the cart total and requires that we recalculate. For this case, we wire in a handler for the PropertyChanged
event whenever we add an item to the cart. This second handler simply recalculates the cart total when the Quantity
property changes.
To wire in this second handler, we depend on the Action property exposed in the CollectionChangedEventArgs ,
which is passed as the second parameter to our first event handler. The actions defined are Add, Remove, and Refresh.
Batch operations such as Load() , Clear() , and Attach() raise the CollectionChangedEvent just once regardless
of how many elements are in the collection. This can be good if your collection contains lots of elements and you
are interested in, as we are here, the entire collection. It can, of course, be annoying if you need to track collection
changes at a more granular level.
 
Search WWH ::




Custom Search