Walkthrough: Binding Silverlight Controls to a WCF Data Service

In this walkthrough, you will create a Silverlight application that contains data-bound controls. The controls are bound to customer records accessed through a WCF Data Service.

This walkthrough illustrates the following tasks:

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

  • Creating a WCF Data Service that exposes the data in the Entity Data Model to a Silverlight application.

  • Running the Data Source Configuration Wizard to connect to the data service which populates the Data Sources window.

  • Creating a set of data-bound controls by dragging items from the Data Sources window to the Silverlight Designer.

  • Creating buttons that navigate forward and backward through records.

    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 Service Project

Start this walkthrough by creating an empty web application project to host a WCF Data Service.

To create the service project

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

  2. Expand Visual C# or Visual Basic, and then select Web.

  3. Select the ASP.NET Empty Web Application project template.

  4. In the Name box, type AdventureWorksWebApp and then click OK.

Creating an Entity Data Model for the Service

To expose data to an application by using a WCF Data Service, a data model must be defined for the service. In this walkthrough, create an Entity Data Model.

To create an Entity Data Model

  1. On the Project menu, click Add New Item.

  2. Select the ADO.NET Entity Data Model project item.

  3. Change the name to AdventureWorksDataModel.edmx, and then click Add.

    The Entity Data Model Wizard opens.

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

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

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

  6. Verify that the Save entity connection settings in Web.Config as option is selected and then click Next.

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

  8. Click Finish.

Creating the Service

Create a WCF Data Service to expose the data in the Entity Data Model.

To create the service

  1. On the Project menu, select Add New Item.

  2. Select the WCF Data Service project item.

  3. In the Name box, type AdventureWorksDataService.svc and then click Add.

Configuring the Service

You must configure the service to operate on the Entity Data Model that you created.

To configure the service

  1. In the AdventureWorksDataService.svc code file, replace the AdventureWorksDataService class declaration with the following code:

    Public Class AdventureWorksDataService
        Inherits DataService(Of AdventureWorksLTEntities)
    
        ' This method is called only once to initialize service-wide policies. 
        Public Shared Sub InitializeService(ByVal config As DataServiceConfiguration)
            config.SetEntitySetAccessRule("*", EntitySetRights.All)
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2
        End Sub 
    
    End Class
    
    public class AdventureWorksDataService : DataService<AdventureWorksLTEntities>
    {
        // This method is called only once to initialize service-wide policies. 
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }
    }
    
  2. Build the project, and verify that it builds without errors.

Creating the Silverlight Application

Create a new Silverlight application, and then add a data source to access the service.

To create the Silverlight application

  1. In Solution Explorer, right-click the solution node, click Add, and select New Project.

  2. In the New Project dialog, expand Visual C# or Visual Basic, and then select Silverlight.

  3. Select the Silverlight Application project template.

  4. In the Name box, type AdventureWorksSilverlightApp and then click OK.

  5. In the New Silverlight Application dialog box, click OK.

Adding the Data Source to the Silverlight Application

Create a data source that is based on the data returned by the service.

To create the data source

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

  2. In the Data Sources window, click Add New Data Source.

    The Data Source Configuration Wizard opens.

  3. In the Choose a Data Source Type page of the wizard, select Service and then click Next.

  4. In the Add Service Reference dialog box, click Discover.

    Visual Studio searches the current solution for available services, and adds AdventureWorksDataService.svc to the list of available services in the Services box.

  5. In the Namespace box, type AdventureWorksService.

  6. In the Services box, click AdventureWorksDataService.svc and then click OK.

  7. In the Add Service Reference page, click Finish.

    Visual Studio adds nodes that represent the data returned by the service to the Data Sources window.

Defining the User Interface of the Window

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

To create the window layout

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

    The window opens in the Silverlight Designer.

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

    <Grid.RowDefinitions>
        <RowDefinition Height="75" />
        <RowDefinition Height="525" />
    </Grid.RowDefinitions>
    <Button HorizontalAlignment="Left" Margin="22,20,0,24" Name="backButton" Width="75" Content="&lt;"></Button>
    <Button HorizontalAlignment="Left" Margin="116,20,0,24" Name="nextButton" Width="75" Content="&gt;"></Button>
    
  3. Build the project.

Creating the Data-bound Controls

Create controls that display customer records by dragging the Customers node from the Data Sources window to the designer.

To create the data-bound controls

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

  2. Expand the Customers node.

  3. 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

    This prevents Visual Studio from creating controls for these nodes when they are dropped onto the designer. For this walkthrough, it is assumed that the end user does not want to see this data.

  4. From the Data Sources window, drag the Customers node to the designer under the buttons.

    Visual Studio generates XAML and code that creates a set of controls that are bound to the customer data.

Load the Data from the Service

Use the service to load data, and then assign the returned data to the data source that is bound to the controls.

To load the data from the service

  1. In the designer, click an empty area next to one of the buttons.

  2. In the Properties window, verify the UserControl is selected and then click the Events tab.

  3. Locate the Loaded event and double-click it.

  4. In the code file that opens (MainPage.xaml) add the following using (C#) or Imports (Visual Basic) statements:

    Imports System.Windows.Data
    Imports AdventureWorksSilverlightApp.AdventureWorksService
    
    using System.Windows.Data;
    using AdventureWorksSilverlightApp.AdventureWorksService;
    
  5. Replace the event handler with the following code. Make sure that you replace the localhost address in this code with the local host address on your development computer:

    Private advWorksService As AdventureWorksLTEntities
    Private customersViewSource As CollectionViewSource
    
    Private Sub UserControl_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        advWorksService = New AdventureWorksLTEntities(New Uri("https://localhost:6188/AdventureWorksDataService.svc"))
        customersViewSource = Me.Resources("CustomersViewSource")
        advWorksService.Customers.BeginExecute(Sub(result As IAsyncResult)
                                                   customersViewSource.Source = advWorksService.Customers.EndExecute(result)
                                               End Sub, Nothing)
    End Sub
    
    private AdventureWorksLTEntities advWorksService;
    private System.Windows.Data.CollectionViewSource customersViewSource;
    
    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        advWorksService = new AdventureWorksLTEntities(new Uri("https://localhost:54961/AdventureWorksDataService.svc"));
    
        customersViewSource = this.Resources["customersViewSource"]
        as System.Windows.Data.CollectionViewSource;
        advWorksService.Customers.BeginExecute(result => customersViewSource.Source = advWorksService.Customers.EndExecute(result), null);
    }
    

Testing the Application

Build and run the application to verify that you can view customer records.

To test the application

  1. On Build menu, click Build Solution. Verify that the solution builds without errors.

  2. Press F5.

  3. Verify the first record in the Customers table appears.

  4. Close the application.

    Note

    If you see an error here verify the code contains the correct port for your ASP.NET Development Server.

Add code that enables scrolling through records by using the < and > buttons.

To enable users to navigate sales records

  1. Open MainPage.xaml in the designer and double-click the < button.

  2. Replace the generated backButton_Click event handler with the following code:

    Private Sub backButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles backButton.Click
        customersViewSource.View.MoveCurrentToPrevious()
        If customersViewSource.View.IsCurrentBeforeFirst Then
            customersViewSource.View.MoveCurrentToFirst()
        End If 
    End Sub
    
    private void backButton_Click(object sender, RoutedEventArgs e)
    {
        customersViewSource.View.MoveCurrentToPrevious();
        if (customersViewSource.View.IsCurrentBeforeFirst)
            customersViewSource.View.MoveCurrentToFirst();
    }
    
  3. Return to the designer, and double-click the > button.

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

  4. Replace the generated nextButton_Click event handler with the following code:

    Private Sub nextButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles nextButton.Click
        customersViewSource.View.MoveCurrentToNext()
        If customersViewSource.View.IsCurrentAfterLast Then
            customersViewSource.View.MoveCurrentToLast()
        End If 
    End Sub
    
    private void nextButton_Click(object sender, RoutedEventArgs e)
    {
        customersViewSource.View.MoveCurrentToNext();
        if (customersViewSource.View.IsCurrentAfterLast)
            customersViewSource.View.MoveCurrentToLast();
    }
    

Testing the Application

Build and run the application to verify that you can view and navigate customer records.

To test the application

  1. On Build menu, click Build Solution. Verify that the solution builds without errors.

  2. Press F5.

  3. Verify the first record in the Customers table appears.

  4. Click the < and > buttons to navigate back and forward through the customer records.

  5. Close the application.

    Note

    If you see an error here verify the code contains the correct port for your ASP.NET Development Server.

Next Steps

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

  • Learn how to save changes back to the database. For more information, see Data Binding.

  • Learn how to incorporate more features using WCF Data Services in Silverlight applications. For more information, see ADO.NET Data Services (Silverlight).

See Also

Other Resources

Data Access and Data Structures