Chapter 6. Northwind—Hierarchical View Model and IoC
By Ryan Vice
In this chapter, we will explore the power of using the Hierarchical View Model approach for building XAML applications. We will use this approach to add the ability to show order details in our application. As we begin to add this functionality, we will take some time to reconsider our design, and look at using an IoC (Inversion of Control) framework to improve our productivity.
Adding orders to customer details
Let's update Northwind to show the orders for each customer in the CustomerDetails.xaml
view as shown in the following screenshot:
The approach we are going to use here is one that I call the Hierarchical View Model or HVM. We've already seen this approach briefly in Chapter 2, Introduction to MVVM, but in this chapter we are going to take a deeper look at this very useful technique.
The way this technique works is by taking advantage of data templates to map Views to View Models. By using this approach, we will be able to add the order details by following these simple steps:
Create OrdersViewModel
.
Create an Orders
View.
Add DataTemplate
to map OrdersViewModel
to OrdersView
.
Add a OrdersViewModel
property called Orders
to CustomeDetailsViewModel
.
Add ContentControl
to CustomerDetailsView
and bind it to CustomerDetailsViewModel.Orders
.
Tip
You might be wondering why we didn't simply add a collection of OrderViewModel
classes directly to CustomerDetailsViewModel...
The next thing we are going to do is add the ability to open an order's details in a new tabbed window and add the ability to close tabs as shown in the following screenshot:
The Order Details view will display all the order line items along with details about the order such as the Shipped Date, Freight, and so on. It allows the user to click on a customer link that will open the that customer's Customer Details view.
We are going to take advantage of HVM to make this easy to accomplish. I have seen people go to great lengths to accomplish tabs in WPF and Silverlight. However, using an MVVM design with HVM makes tabbed interfaces very easy to implement.
Currently, our MainWindowViewModel
owns the responsibility for opening tools but under our new design we want to be able to open an order's details from the order details row as shown in the following screenshot:
To accomplish this we are going to refactor out the tool management behind a new IToolManager
interface...
This brings us to the end of our implementation of Northwind. In this chapter, we saw how, as the complexity of our application grew, we could make things easier by using the HVM approach and using an IoC container to help with application composition. We looked at IoC's best practices and looked at a lot of the issues that can pop up when using IoC containers along with approaches for avoiding these issues.