I’m using MVVM in WPF in C#.NET. Say I have the following example model:
public class Dealer
{
public string Name { get; set; }
public List<Car> Cars { get; set; }
}
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
}
In my view, I have a list of dealers, and if I select a dealer in the ListView, then I should see details about the dealer, including the dealer’s name and the list of cars.
My question is, how can I bind the List of Cars to a list view, given that it’s a property of the Dealer object? Specifically, what should I have in my view model? I need the list of cars to update if I add anything to the collection, so I have a feeling that I’ll need an ObservableCollection. However, this seems to lead to having two collections (a List and an ObservableCollection) for every dealer, and having this duplication of data seems inefficient from both a coding point of view and performance. Any ideas?
What we have been doing is wrapping the Model lists within an ObservableCollection. This ObservableCollection is usually also a ViewModel for the Child object, so we can control its view and be able to pass the ViewModel to another view when necessary. You will have two lists, but they will contain the same object references. It may seem like a duplication of effort, but with a decent use of Inheritance, you can still maintain a DRY approach. Remember the idea of MVVM is to create an Abstraction between your View and the Model, it may seem like you are saving yourself the effort upfront by not wrapping the Child objects, however we have found that there is almost always a need to tranform these Child objects later.