MVVM/WPF: Using a ObservableCollection<T> as a list in a domain model, is that good/bad?
I have aggregated models like Customer:Order:Product.
As my View is bound to the BillingViewModel which has a Property Customers of type ObservableCollection
and ONE customer in this collection has a "list" of orders named ObservableCollection
and ONE order in this collection has a "list" of products named ObservableCollection
Well I need the ObservableCollection`s for databinding but should a domain model really have a ObservableCollection ? normally it has a
List or IEnumerable !
开发者_高级运维Is this bad habit or having side effects?
I append an explanation to the above what is right:
class Customer
{
int CustomerID {get;set;}
ObservableCollection<Order> { get;set;}
}
class BillingViewModel
{
ObservableCollection<Customer> _customers;
public BillingViewModel()
{
Customers= GetAggregatedCustomersOrdersProductsFromRepository();
}
public ObservableCollection<Customer> Customers
{
get{ return _customers;}
set
{
_customers = value;
this.RaisePropertyChanged("Customers");
}
}
}
I hope its more clear now! I have ObservableCollection in my ViewModel and Model!
From the examples I have read it appears that one practices is to take your Domain model Customer:Order:Product and rearrange it into MainViewModel:CustomerViewModel:OrderViewModel:ProductViewModel when it reaches the client side. This would allow you to mark any of the VMs dirty and save only when needed. It would also allow you to compose your View of many Views each driven by their own VM, so if later you decided to change the View from one large Screen into many Modals it would be fairly seamless. The reason for the MainViewModel, is more of a Controller then a ViewModel, its duty would be to get the Domain Model and break it apart into the VMs and also could be the Controller for how your Views will be displayed (Grouped or Modal), it could also contain Commands such as SaveAllDirty.
It depends on if those properties need the built in change notification. If you have some kind of logic that depends on doing something when those change state, then it's fine. If it's only there to support data binding and that class is not itself a ViewModel, then I think it's bad form.
精彩评论