Walkthrough: Binding WPF Controls to an Entity Data Model

In this walkthrough, you will create a WPF application that contains data-bound controls. The controls are bound to customer records that are encapsulated in an Entity Data Model. You will also add buttons that customers can use to navigate through customer records and save changes to records.

This walkthrough illustrates the following tasks:

  • Creating a WPF application and an Entity Data Model that is generated from data in the AdventureWorksLT sample database.

  • Creating a set of data-bound controls by dragging an entity from the Data Sources window to a window in the WPF designer.

  • Creating buttons that navigate forward and backward through customer records.

  • Creating a button that saves changes in the controls to the Entity Data Model and the underlying data source.

    Note

    Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

Prerequisites

You need the following components to complete this walkthrough:

  • Visual Studio

  • Access to a running instance of SQL Server or SQL Server Express that has the AdventureWorksLT sample database attached to it. You can download the AdventureWorksLT database from the CodePlex Web site.

Prior knowledge of the following concepts is also helpful, but not required to complete the walkthrough:

Creating the Project

Create a new WPF project to display the customer records.

To create the project

  1. Start Visual Studio.

  2. On the File menu, point to New, and then click Project.

  3. Expand Visual Basic or Visual C#, and then select Windows.

  4. Select the WPF Application project template.

  5. In the Name box, type AdventureWorksCustomerEditor and then click OK.

    Visual Studio creates the AdventureWorksCustomerEditor project.

Creating an Entity Data Model for the Application

Before you can create data-bound controls, you must define a data model for your application and add it to the Data Sources window. In this walkthrough, you create an Entity Data Model.

To create an Entity Data Model

  1. On the Data menu, click Add New Data Source to open the Data Source Configuration Wizard.

  2. On the Choose a Data Source Type page, click Database, and then click Next.

  3. On the Choose a Database Model page, click Entity Data Model, and then click Next.

  4. On the Choose Model Contents page, click Generate from database, and then click Next.

  5. On the Choose Your Data Connection page, do one of the following:

    • If a data connection to the AdventureWorksLT sample database is available in the drop-down list, select it.

      -or-

    • Click New Connection and create a connection to the AdventureWorksLT database.

    Make sure that the Save entity connection settings in App.Config as option is selected, and then click Next.

  6. On the Choose Your Database Objects page, expand Tables, and then select the Customer table.

  7. Click Finish.

    The Model1.edmx file opens in the designer.

  8. Build the project.

Defining the User Interface of the Window

Add buttons to the window by modifying the XAML in the WPF Designer.

To define the user interface of the window

  1. In Solution Explorer, double-click MainWindow.xaml.

    The window opens in the WPF Designer.

  2. In the XAML view of the designer, add the following code between the <Grid> tags:

    <Grid.RowDefinitions>
         <RowDefinition Height="75" />
         <RowDefinition Height="425" />
    </Grid.RowDefinitions>
    <Button HorizontalAlignment="Left" Margin="22,20,0,24" Name="backButton" Width="75">&lt;</Button>
    <Button HorizontalAlignment="Left" Margin="116,20,0,24" Name="nextButton" Width="75">&gt;</Button>
    <Button HorizontalAlignment="Right" Margin="0,21,46,24" Name="saveButton" Width="110">Save changes</Button>
    
  3. Build the project.

Creating Data-Bound Controls

Create controls that display customer records by dragging objects from the Data Sources window to the WPF Designer.

To create data-bound controls

  1. On the Data menu, click Show Data Sources.

  2. In the Data Sources window, click the drop-down menu for the Customers node and select Details.

  3. Expand the Customers node.

  4. For this example some fields will not be displayed so click the drop-down menu next to the following nodes and select None:

    • NameStyle

    • PasswordHash

    • PasswordSalt

    • rowGuid

    • ModifiedDate

  5. From the Data Sources window, drag the Customers node to the area under the buttons.

  6. In the designer, click the text box next to the Customer ID label.

  7. In the Properties window, select the check box next to the IsReadOnly property.

  8. Build the project.

Add code that enables users to scroll through customer records by using the < and > buttons.

To enable users to navigate customer records

  1. In the designer, double-click the < button.

    Visual Studio opens the code-behind file and creates a new backButton_Click event handler for the Click event.

  2. Modify the Window_Loaded event handler so the CustomersViewSource and AdventureWorksLTEntities are outside of the method and accessible to the entire form. Only declare these global to the form, assign them within the Window_Loaded event handler similar to the following:

    Dim CustomersViewSource As System.Windows.Data.CollectionViewSource
    Dim AdventureWorksLTEntities As AdventureWorksCustomerEditor.AdventureWorksLTEntities
    
    
    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        CustomersViewSource = CType(Me.FindResource("CustomersViewSource"), System.Windows.Data.CollectionViewSource)
        AdventureWorksLTEntities = New AdventureWorksCustomerEditor.AdventureWorksLTEntities()
        'Load data into Customers. You can modify this code as needed. 
        Dim CustomersQuery As System.Data.Objects.ObjectQuery(Of AdventureWorksCustomerEditor.Customer) = Me.GetCustomersQuery(AdventureWorksLTEntities)
        CustomersViewSource.Source = CustomersQuery.Execute(System.Data.Objects.MergeOption.AppendOnly)
    End Sub
    
    private System.Windows.Data.CollectionViewSource customersViewSource;
    private AdventureWorksCustomerEditor.AdventureWorksLTEntities adventureWorksLTEntities;
    
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        adventureWorksLTEntities = new AdventureWorksCustomerEditor.AdventureWorksLTEntities();
        // Load data into Customers. You can modify this code as needed.
        customersViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("customersViewSource")));
        System.Data.Objects.ObjectQuery<AdventureWorksCustomerEditor.Customer> customersQuery = this.GetCustomersQuery(adventureWorksLTEntities);
        customersViewSource.Source = customersQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
    }
    
  3. Add the following code to the backButton_Click event handler:

    If CustomersViewSource.View.CurrentPosition > 0 Then
        CustomersViewSource.View.MoveCurrentToPrevious()
    End If
    
    if (customersViewSource.View.CurrentPosition > 0)
        customersViewSource.View.MoveCurrentToPrevious();
    
  4. Return to the designer, and double-click the > button.

    Visual Studio opens the code-behind file and creates a new nextButton_Click event handler for the Click event.

  5. Add the following code to the nextButton _Click event handler:

    If CustomersViewSource.View.CurrentPosition < CType(CustomersViewSource.View, CollectionView).Count - 1 Then
        CustomersViewSource.View.MoveCurrentToNext()
    End If
    
    if (customersViewSource.View.CurrentPosition < ((CollectionView)customersViewSource.View).Count - 1)
        customersViewSource.View.MoveCurrentToNext();
    

Checkpoint

Build and run your project to make sure that the code compiles, and that you can navigate customer records.

To test the application

  • Press F5.

    The application builds and runs. Verify the following:

    • Customer data is displayed.

    • You can click the > or < buttons to navigate customer records.

Saving Changes to Customer Records

Add code that enables users to save changes to customer records by using the Save changes button.

To add the ability to save changes to customer records

  1. In the designer, double-click the Save changes button.

    Visual Studio opens the code-behind file and creates a new saveButton_Click event handler.

  2. Add the following code to the saveButton_Click event handler:

    AdventureWorksLTEntities.SaveChanges()
    
    adventureWorksLTEntities.SaveChanges();
    

Testing the Application

Build and run the application to verify that it displays the customer records and enables you to save changes to them.

To test the application

  1. Press F5.

  2. Edit one of the customer records and then click Save changes.

  3. Close the application, and then start the application again by pressing F5.

  4. Navigate to the customer record you changed, and verify that the change has persisted.

  5. Close the application.

Next Steps

After completing this walkthrough, you can perform the following related tasks:

See Also

Tasks

How to: Bind WPF Controls to Data in Visual Studio

Walkthrough: Binding WPF Controls to a Dataset

Walkthrough: Binding WPF Controls to a WCF Data Service

Concepts

Binding WPF Controls to Data in Visual Studio

WPF and Silverlight Designer Overview

Data Binding Overview

Other Resources

Introducing the Entity Framework