5 out of 8 rated this helpful - Rate this topic

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.

    NoteNote

    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.

You need the following components to complete this walkthrough:

  • Visual Studio 2010.

  • 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:

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.

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.

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.

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:

    
    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)
        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 < ((CollectionView)customersViewSource.View).Count - 1)
        customersViewSource.View.MoveCurrentToNext();
    
    
    

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.

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();
    
    
    

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.

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

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Cannot add the control to the design surface or bind to the control
INITIAL POST
--------------

If your project is NOT on the C: drive then we can NOT get this example to work.
This appears to be a common problem. I am having it, and others are having it.

Here are other examples of the problem:
http://social.msdn.microsoft.com/Forums/da-DK/vswpfdesigner/thread/9fc4f835-d6c0-4d04-86c2-779c1f8e0791
http://int.social.msdn.microsoft.com/Forums/en/vswpfdesigner/thread/32c3dd42-fa00-4218-bb78-d6f1bbbe86dd

MORE INFORMATION
-------------------------

1] I redid the example, step by step on the C: drive. Once it was built and running as described in the article I closed the project and copied it to a network drive.
I got a similar "ERROR", i.e. the designer had a message:

"Problem Loading" "The document contains errors that must be fixed before the designer can be loaded. Reload the designer after you have fixed the errors"

When I clicked on the "Reload the designer" link I got this message in the Error List:

"Error    1    Unable to load the metadata for assembly 'AdventureWorksCustomerEditor'. This assembly may have been downloaded from the web.  See http://go.microsoft.com/fwlink/?LinkId=179545.  The following error was encountered during load: Could not load file or assembly 'AdventureWorksCustomerEditor' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)    P:\prj_0000_General\TESTING_vb_Project\AdventureWorksCustomerEditor\AdventureWorksCustomerEditor\MainWindow.xaml    1    1    AdventureWorksCustomerEditor"

HOWEVER the application did 'build' and 'run', and it seemed to be saving the edits to the database.

2] The information in the article (i.e. 179545) was not helpful, b/c it directs you to a) to into explorer, and b) "Right-click the assembly". I am not sure which file they are referring to exactly (i specifically tried the file: MainWindow.xaml , in addition to others) , but none of the files appeared to have an "Unblock" button. Rebuilding did not resolve the problem.

3] Research led me to article: http://msdn.microsoft.com/en-us/library/dd409252.aspx\
 
I added the following:    <loadFromRemoteSources enabled="true"/>
Into the file:   devenv.exe.config
Located in directory:  C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE

The string that was added was loaded into the XML, of the file 'devenv.exe.config'  more-or-less following the following pattern:
<configuration>
   <runtime>
      <loadFromRemoteSources enabled="true"/>
   </runtime>
</configuration>

That resolved the problem. You should read the last article to understand the associated issues.

Clarification
$0$0 $0To create data-bound controls$0 $0 $0 $0 $0On the Data menu, click Show Data Sources.$0 $0 $0 $0In the Data Sources window, click the drop-down menu for the Customers node and select Details.$0 $0 $0 $0Expand the Customers node.$0 $0 $0 $0For this example some fields will not be displayed so click the drop-down menu next to the following nodes and select None:$0 $0 $0 $0NameStyle$0 $0 $0 $0PasswordHash$0 $0 $0 $0PasswordSalt$0 $0 $0 $0rowGuid$0 $0 $0 $0ModifiedDate$0 $0 $0 $0 $0 $0From the Data Sources window, drag the Customers node to the area under the buttons.$0 $0 $0 $0In the designer, --- in the XAML tab, not the Design tab, highlight the line of XAML code that defines -- the Customer ID label.$0 $0 $0 $0In the Properties window, select the check box next to the IsReadOnly property.$0 $0 $0 $0Build the project.$0 $0 $0 $0 .