Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF

You're reading from  MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF

Product type Book
Published in Aug 2012
Publisher Packt
ISBN-13 9781849683425
Pages 490 pages
Edition 1st Edition
Languages

Table of Contents (21) Chapters

MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF
Credits
Foreword
About the Authors
About the Reviewer
www.PacktPub.com
Preface
1. Presentation Patterns 2. Introduction to MVVM 3. Northwind – Foundations 4. Northwind—Services and Persistence Ignorance 5. Northwind—Commands and User Inputs 6. Northwind—Hierarchical View Model and IoC 7. Dialogs and MVVM 8. Workflow-based MVVM Applications 9. Validation 10. Using Non-MVVM Third-party Controls 11. MVVM Application Performance MVVM Frameworks
Binding at a Glance Index

Chapter 3. Northwind – Foundations

By Ryan Vice

Now that we've laid a solid foundation by covering the history of presentation patterns and by building the Project Billing sample in MVVM, we are ready for a deeper dive that will take us beyond "Hello World" applications and into the real world of enterprise MVVM development. One of the key goals of this book is to provide comprehensive coverage of MVVM that will guide you through the many architectural decisions that need to be made when designing and building MVVM applications. If you are a one-man team building an internal intranet application that serves a small number of users, then you should have a much simpler design than if you were building the next http://www.amazon.com/.

Our goal is to educate you on not just the "hows" but also the "whys" of each technique that we introduce. This will allow you to find the right balance in your design, and help you to avoid over-engineering or under-engineering your solution. To help us accomplish...

Northwind requirements


Northwind is a sample database released by Microsoft that contains the sales data for a fictitious company called Northwind Traders, which imports and exports specialty foods from around the world. We will be building an application based on the Northwind database that will support:

  • Selecting a customer from a list of current customers, and viewing the selected customer's details and order history with support for editing the customer's details

  • Selecting an order by ID and viewing the order details including the company's information, sales contact and an invoice summary (products purchased, quantities, prices, and so on)

  • Ability to create a new order

This is far from a complete application, but is complex enough to allow us to demonstrate all the tools and techniques that would be needed to create a full LOB application using MVVM.

The UI of this application is shown in the following screenshot:

Presentation tier foundation


Let's start things off by creating the visual layout of our application by following these steps:

  1. Start a new Visual Studio instance.

  2. Create a new WPF application project called Northwind.UI.WPF, and name the solution Northwind.

  3. Add a folder to Northwind.UI.WPF called Skins, and add a new Resource Dictionary (WPF) file to that folder called MainSkin.xaml.

  4. Open MainWindow.xaml for editing and update it as follows:

    <Window x:Class="Northwind.UI.WPF.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/
            2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow"
            MinHeight="350"
            MinWidth="525"
            xmlns:ViewModel="clr-namespace:Northwind.ViewModel;
            assembly=Northwind.ViewModel"
            DataContext="{Binding 
                Source={x:Static 
                ViewModel:ViewModelLocator
                    .MainWindowViewModelStatic}}">
        <Window.Resources>
            <ResourceDictionary...

Data access tier


Now we need to get our data access sorted out. We will show a few different options for data access throughout this book. For our first pass, we will keep things simple and use the entity framework to get up and running quickly. Let's start by following these steps:

Tip

If you are not running Visual Studio as an administrator, then you need to close it and restart it as the administrator. On Windows 7, this is done by right-clicking on the program icon in the Start menu, and then selecting Run as administrator.

  1. Download Northwind database.

    Note

    At the time of writing this book, the database could be downloaded from http://archive.msdn.microsoft.com/northwind/Release/ProjectReleases.aspx?ReleaseId=1401. If that URL is no longer working, then use your favorite search engine to find the Northwind sample database and download it.

  2. Unzip the downloaded file and take note of the location of the Northwind.mdf file that was a part of the download.

    Tip

    If you are not running Visual Studio...

Listing the customers


The next thing we need to do is to get a list of customers to display in the UI. Our approach will be to create a data provider that will query the entity framework to get our entities, which we will use as our models. To accomplish this, follow these steps:

  1. Add a project reference from Northwind.ViewModel to Northwind.Data.

  2. Add a .NET reference to System.Data.Entity.

  3. Add using statements for System.Collections.Generic, Northwind.Data, and System.Data.Objects to MainWindowViewModel.

  4. Add the following code to MainWindowViewModel:

    private IList<Customer> _customers;
    
    public IList<Customer> Customers
    {
        get 
        {
            if (_customers == null)
            {
                GetCustomers();
            }
            return _customers; 
        }
    }
    
    private void GetCustomers()
    {
        _customers 
            = new NorthwindEntities()
                .Customers.ToList();
    }
  5. Update Expander in MainWindow as shown in the following code:

    <Expander Padding="10"
              Margin="4"
              BorderBrush...

Adding tabs


As shown in the requirements section earlier, in this chapter, our Northwind application needs to support a tabbed display. MVVM greatly simplifies the creating and managing of tabs as you can have the binding system map views to view models. This makes adding a tabbed interface to our UI a simple matter of using the Hierarchical View Model approach along with some basic OOD techniques.

Note

Hierarchical View Model will be discussed in detail in Chapter 6, Hierarchical View Model and IoC.

To accomplish this, follow the steps listed here:

  1. Add a new class called ToolViewModel.cs to the Northwind.ViewModel project, and update the code as follows:

    namespace Northwind.ViewModel
    {
        public class ToolViewModel
        {
            public string DisplayName { get; set; }
        }
    
        public class AToolViewModel : ToolViewModel
        {
            public AToolViewModel()
            {
                DisplayName = "A";
            }
        }
    
        public class BToolViewModel : ToolViewModel
        {
            public BToolViewModel...

Viewing customer details


Next, we will be updating Northwind to allow us to view customer details.

Viewing details for one customer

We will view the details for one customer by opening a tab for each customer detail in the UI using the technique that we just covered. We will start things off by creating the ToolViewModel derived view model and its associated view (UserControl). We will then connect the pieces using a data template to map our view to our view model. To do this, perform the following steps:

  1. Update the IUIDataProvider interface to add the following method:

    Customer GetCustomer(string customerID);
  2. Update UIDataProvider as follows:

    public class UIDataProvider : IUIDataProvider
    {
        private NorthwindEntities _northwindEntities
            = new NorthwindEntities();
    
        public IList<Customer> GetCustomers()
        {
            return _northwindEntities.Customers.ToList();
        }
    
        public Customer GetCustomer(string customerID)
        {
            return
                _northwindEntities.Customers...

Wiring up the customer list box


Now, we need to make the tabs dynamic and wire them up to the customer list box. To do this follow these steps:

  1. Update MainWindow.xaml as follows:

        </Expander.Header>
        <StackPanel>
            <ListBox ItemsSource="{Binding Customers}" 
                        DisplayMemberPath="CompanyName"
                        SelectedValuePath="CustomerID"
                        VerticalAlignment="Top"
                        SelectedValue
    ="{Binding 
                            SelectedCustomerID}"
                        Height="180"
                        Width="250" />
            <ContentControl Margin="0, 3">
                <Hyperlink Click="Hyperlink_Click">
                    <TextBlock Text="Show Details" />
                </Hyperlink>
            </ContentControl>
        </StackPanel>                    
    </Expander>
  2. Add a using statement for Northwind.ViewModel in MainWindow.xaml.cs.

  3. Add the following function to MainWindow in MainWindow.xaml.cs...

Summary


In this chapter, we've laid the foundation for our application. We started things off by introducing the requirements of the Northwind application. Next, we demonstrated a quick way to get up and running with a database-driven MVVM application by using Microsoft's entity framework. We followed this up by refactoring our design to improve testability, and added our first unit tests. We then looked at how to easily create dynamic workspaces using MVVM by adding a tabbed interface to Northwind. We finished the chapter by looking at the entity framework's support for change notifications.

lock icon The rest of the chapter is locked
You have been reading a chapter from
MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF
Published in: Aug 2012 Publisher: Packt ISBN-13: 9781849683425
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime}