- UI Design Patterns
- The Model-View-ViewModel Pattern
- Binding the View Model to the View
- Lists and Data Elements
- Summary
Lists and Data Elements
One situation you might find confusing when using the MVVM model is how to handle lists. Although it’s clear that you may have a view model for a list of contacts that provides a list of contact items, it’s not as clear how to manage displaying those contacts in an editable grid. Do you have to create a view model for each contact? Is it a violation of MVVM if the contacts implement property-change notification directly?
These questions are really a matter of splitting hairs rather than solving the problem. The answer is to define the solution that makes the most sense. In most cases, implementing property-change notification on the individual items is fine. The overhead of wrapping each item in a view model doesn’t make sense when so much logic is duplicated. By default, Silverlight client proxies for web services will implement property-change notification for complex data types. You can also specify a shared assembly to define the type directly, and inherit from a simple base type to implement the property-change notification.
Each item can then be tracked for edits. When common commands can be performed, such as a delete command, the item can be passed to a command on the parent view model so the logic is maintained in one central place. This keeps the overall approach simple and straightforward. If you end up implementing a detail screen that has a dedicated view model, you can refactor the grid to use the same view model if it makes sense.
The Silverlight framework provides the ObservableCollection class for managing lists that may change. This special collection will raise a collection-change notification. This can be used by UI elements to refresh their contents and by your code to respond to changes in the list. If each individual item also has significant presentation logic, you may end up projecting the list to a collection of view model items.
There are no hard-and-fast rules. MVVM is about making it easier to develop applications by taking advantage of code reuse and the built-in data-binding system that Silverlight uses. If you find that using MVVM is making your project more complex and difficult to maintain, you’re likely doing it wrong and should take a step back to reevaluate your approach. The next few chapters will cover some ways to make sure you’re reaping the benefits of MVVM.