I am working with WPF+MVVM
.
I have a VM
which contains a Customer
property. The Customer
has an ObservableCollection
of Orders
. Each Order
has an ObservableCollection
of Items
. Each Items
has a Price
.
Now, I have the following property on my VM
:
public double TotalPrice
{
return Customer.Orders.Sum(x => x.Items.Sum(y => y.Price));
}
The problem is whenever a change occurs at any point in this graph of objects - the UI should be notified that TotalPrice
had changed - but it doesn't...
For example if the Customer
will be altered from A to B, or an order will be added, or an item will be deleted, or an item's price will be altered etc.
Does anyone has an elegant solution for this?
Thanks.
Have you supported INotifyPropertyChanged / INotifyCollectionChanged interfaces in ViewModels? You should be able trigger any property manually, for instance in setter of any property you can trigger OnPropertyChanged("TotalPrice")
so UI bindings for TotalPrice
would be updated as well.
To handle dependent objects changes you can provide events or something like that so ViewModel would be able to subscribe and handle underlying object changes, for instance you have some service which is in chanrge of reloading of the Orders from a database, so as soo as new changes come you would update UI as well. In this case OrdersService
should expose event OrdersUpdated
and ViewModel can subscribe for this event and in trigger PropertyChanged
events for affected properties.
Let's consider some case as an example, for instance Order price has been changed. Who is in charge of this changes? Is this done via UI by an user?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With