Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A MVVM pitfall using Master-Detail scenario

Either I do not see the solution or I found a pitfall in using MVVM.

I have this sample Master-Detail:

class Customer
{
    int CustomerID {get;set}
    string Name {get;set}
    ObservableCollection<Order> Orders {get;set}
}

class Order
{
    int OrderID {get;set}
    int Quantity {get;set}
    double Discount {get;set}
}

Lets assume in my CustomerOrdersViewModel my ObservableCollection Customers is bound to the View via ...="{Binding Customers}" and when the customer is changed from the user the relating Orders are shown in the DataGrid via ItemsSource="{Binding SelectedItem.Orders, ElementName=comboboxCustomer}".

This is possible with MVVM:

I can add a new Customer by simply (for simplicity's sake) calling Customers.Add(new Customer(){...});.

After the adding I do this: this.RaisePropertyChanged("Customers");. This will update the view and immediately show the Customer in the Customer-Combobox.

Now comes the impossible part with MVVM.

I can add a new Order by SelectedCustomer.Orders.Add(New Order(){...});

BUT I cannot raise a CollectionChanged/PropertyChanged event like before with the Customers now on the Orders because the Orders Property is not bound to the View via public accessor.

Even if I would expose Orders bindable property to the view, the view itself cares for the Master-Detail switching not the ViewModel...

QUESTION

How is it possible to make Master-Detail work with Add/Del objects in Details-List and immediate update on the View?

like image 811
msfanboy Avatar asked Feb 27 '10 19:02

msfanboy


1 Answers

This is always difficult, when working with master-detail views. However, one option is typically to take advantage of INotifyPropertyChanged and INotifyCollectionChanged, and track these yourself in the ViewModel. By tracking these properties on your objects, you can handle notifications correctly.

I blogged about a similar issue, where I wanted to have aggregation happening in the "master" list based on values in the details pane (ie: show a total # of orders, that would always be up to date). The issues are identical.

I put some working code up on the Expression Code Gallery demonstrating how you can handle this tracking, and make everything stay up to date in real time, while still staying "pure" in MVVM terms.

like image 55
Reed Copsey Avatar answered Nov 02 '22 16:11

Reed Copsey