Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM property depends on a graph of objects

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.

like image 548
Mosi Altman Avatar asked Oct 10 '22 07:10

Mosi Altman


1 Answers

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?

like image 151
sll Avatar answered Oct 13 '22 12:10

sll