Share via


How to: Bind Data Using a Project Data Source (WCF Data Services)

You can create data sources that are based on the generated data objects in an WCF Data Services client application. When you add a reference to a data service by using the Add Service Reference dialog, a project data source is created along with the generated client data classes. One data source is created for each entity set that the data service exposes. You can create forms that display data from the service by dragging these data source items from the Data Sources window onto the designer. These items become controls that are bound to the data source. During execution, this data source is bound to an instance of the DataServiceCollection class, which is filled with objects that are returned by a query to the data service. For more information, see Binding Data to Controls (WCF Data Services)

The examples in this topic use the Northwind sample data service and autogenerated client data service classes. This service and the client data classes are created when you complete the WCF Data Services quickstart.

To use a project data source in a WPF window

  1. In a WPF project, add a reference to the Northwind data service. For more information, see How to: Add a Data Service Reference (WCF Data Services).

  2. In the Data Sources window, expand the Customers node in the NorthwindEntities project data source.

  3. Click the CustomerID item, select ComboBox from the list, and drag the CustomerID item from the Customers node to the designer.

    This creates the following object elements in the XAML file for the window:

  4. Drag the Orders navigation property to the designer.

    This creates the following additional object elements in the XAML file for the window:

    • A second CollectionViewSource element named customersOrdersViewSource, the source of which is the customerViewSource.

    • A data-bound DataGrid control named ordersDataGrid.

  5. (Optional) Drag additional items from the Customers node to the designer.

  6. Open the code page for the form and add the following using statements (Imports in Visual Basic):

    using System.Data.Services.Client;
    using NorthwindClient.Northwind;
    
  7. In the partial class that defines the form, add the following code that creates an ObjectContext instance and defines the customerID constant.

    Private context As NorthwindEntities
    Private customersViewSource As CollectionViewSource
    Private trackedCustomers As DataServiceCollection(Of Customer)
    Private Const customerCountry As String = "Germany"
    Private Const svcUri As String = "https://localhost:12345/Northwind.svc/"
    
    private NorthwindEntities context;
    private CollectionViewSource customersViewSource;
    private DataServiceCollection<Customer> trackedCustomers;
    private const string customerCountry = "Germany";
    private const string svcUri = "https://localhost:12345/Northwind.svc/";
    
  8. In the designer, select the window.

    Note

    Make sure that you select the window itself, rather than selecting content that is within the window. If the window is selected, the Name text box near the top of the Properties window should contain the name of the window.

  9. In the Properties window, select the Events button.

  10. Find the Loaded event, and then double-click the drop-down list next to this event.

    Visual Studio opens the code-behind file for the window and generates a Loaded event handler.

  11. In the newly created Loaded event handler, copy and paste the following code.

    ' Initialize the context for the data service.
    context = New NorthwindEntities(New Uri(svcUri))
    
    ' Create a LINQ query that returns customers with related orders.
    Dim customerQuery = From cust In context.Customers.Expand("Orders") _
                             Where cust.Country = customerCountry _
                             Select cust
    
    ' Create a new collection for binding based on the LINQ query.
    trackedCustomers = New DataServiceCollection(Of Customer)(customerQuery)
    
        try
            ' Get the customersViewSource resource and set the binding to the collection.
        customersViewSource = _
            CType(Me.FindResource("customersViewSource"), CollectionViewSource)
        customersViewSource.Source = trackedCustomers
        customersViewSource.View.MoveCurrentToFirst()
    Catch ex As DataServiceQueryException
        MessageBox.Show("The query could not be completed:\n" + ex.ToString())
    Catch ex As InvalidOperationException
        MessageBox.Show("The following error occurred:\n" + ex.ToString())
    End Try
    
    // Initialize the context for the data service.
    context = new NorthwindEntities(new Uri(svcUri));
    
    // Create a LINQ query that returns customers with related orders.
    var  customerQuery = from cust in context.Customers.Expand("Orders")
                         where cust.Country == customerCountry
                         select cust;
    
    // Create a new collection for binding based on the LINQ query.
    trackedCustomers = new DataServiceCollection<Customer>(customerQuery);
    
    try
    {
        // Get the customersViewSource resource and set the binding to the collection.
        customersViewSource =
            ((CollectionViewSource)(this.FindResource("customersViewSource")));
        customersViewSource.Source = trackedCustomers;
        customersViewSource.View.MoveCurrentToFirst();
    }
    catch (DataServiceQueryException ex)
    {
        MessageBox.Show("The query could not be completed:\n" + ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        MessageBox.Show("The following error occurred:\n" + ex.ToString());
    }
    
  12. This code creates an instance of DataServiceCollection for the Customers type based on the execution of a LINQ query that returns an IEnumerable of Customers along with related Orders objects from the Northwind data service and binds it to the customersViewSource.

To use a project data source in a Windows form

  1. In the Data Sources window, expand the Customers node in the NorthwindEntities project data source.

  2. Click the CustomerID item, select ComboBox from the list, and drag the CustomerID item from the Customers node to the designer.

    This creates the following controls on the form:

    • An instance of BindingSource named customersBindingSource.

    • An instance of BindingNavigator named customersBindingNavigator. You can delete this control as it will not be needed.

    • A data-bound ComboBox named CustomerID.

    • A Label.

  3. Drag the Orders navigation property to the form.

  4. This creates the ordersBindingSource control with the DataSource property of the control set to the customersBindingSource and the DataMember property set to Customers. It also creates the ordersDataGridView data-bound control on the form, accompanied by an appropriately titled label control.

  5. (Optional) Drag additional items from the Customers node to the designer.

  6. Open the code page for the form and add the following using statements (Imports in Visual Basic):

    Imports System.Data.Services.Client
    Imports NorthwindClient.Northwind
    
    using System.Data.Services.Client;
    using NorthwindClient.Northwind;
    
  7. In the partial class that defines the form, add the following code that creates an ObjectContext instance and defines the customerID constant.

    Private context As NorthwindEntities
    Private trackedCustomers As DataServiceCollection(Of Customer)
    Private Const customerCountry As String = "Germany"
    Private Const svcUri As String = "http:'localhost:12345/Northwind.svc/"
    
    private NorthwindEntities context;
    private DataServiceCollection<Customer> trackedCustomers;
    private const string customerCountry = "Germany";
    private const string svcUri = "https://localhost:12345/Northwind.svc/";
    
  8. In the form designer, double-click the form.

    This opens the code page for the form and creates the method that handles the Load event for the form.

  9. In the Load event handler, copy and paste the following code.

    ' Initialize the context for the data service.
    context = New NorthwindEntities(New Uri(svcUri))
    Try
        ' Create a LINQ query that returns customers with related orders.
        Dim customerQuery = From cust In context.Customers.Expand("Orders") _
                                Where cust.Country = customerCountry _
                                Select cust
    
        ' Create a new collection for binding based on the LINQ query.
        trackedCustomers = New DataServiceCollection(Of Customer)(customerQuery)
    
        'Bind the Customers combobox to the collection.
        customersComboBox.DisplayMember = "CustomerID"
        customersComboBox.DataSource = trackedCustomers
    Catch ex As DataServiceQueryException
        MessageBox.Show("The query could not be completed:\n" + ex.ToString())
    Catch ex As InvalidOperationException
        MessageBox.Show("The following error occurred:\n" + ex.ToString())
    
    // Initialize the context for the data service.
    context = new NorthwindEntities(new Uri(svcUri));
    try
    {
        // Create a LINQ query that returns customers with related orders.
        var customerQuery = from cust in context.Customers.Expand("Orders")
                            where cust.Country == customerCountry
                            select cust;
    
        // Create a new collection for binding based on the LINQ query.
        trackedCustomers = new DataServiceCollection<Customer>(customerQuery);
    
        //Bind the Customers combobox to the collection.
        customersComboBox.DisplayMember = "CustomerID";
        customersComboBox.DataSource = trackedCustomers;
    }
    catch (DataServiceQueryException ex)
    {
        MessageBox.Show("The query could not be completed:\n" + ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        MessageBox.Show("The following error occurred:\n" + ex.ToString());
    }
    
  10. This code creates an instance of DataServiceCollection for the Customers type based on the execution of a DataServiceQuery that returns an IEnumerable of Customers from the Northwind data service and binds it to the customersBindingSource.

See Also

Tasks

How to: Bind Data to Windows Presentation Foundation Elements (WCF Data Services)

Other Resources

WCF Data Services Client Library