This blog post is an update to an introduction to the data binding capabilities we first added in Data Services v1.5 CTP1. We have taken the feedback received throughout the CTPs and made updates to the final design. Below is an update to the original binding post for CTP1 updated based on that feedback.

Introduction to Data Binding

A new collection type, DataServiceCollection, has been added to the client library which extends ObservableCollection and supports two way binding for client code. It is now possible to auto generate client side types that implement the INotifyPropertyChanged and INotifyCollectionChanged interfaces using the add service reference gesture.

This means that, when data binding has been enabled, any changes made to contents of a DataServiceCollection or the entities in the collection will be reflected on the client context; any subsequent calls to SaveChanges() on that context will then persist those changes on the service. As well, any changes made to the entities in the context, through a subsequent query to the data service, will automatically be reflected on the items in the DataServiceCollection.

This also means that the DataServiceCollection, because it implements the standard binding interfaces, can be bound as the DataSource to most WPF and Silverlight controls.

Here are some examples of different ways to create a DataServiceCollection using the ADO.NET Data Services client library. In all of these examples, the queries are being executed against a service named “nwsvc” that exposes two types: products and suppliers that have a one-to-many relationship.

Example 1: Creating a DataServiceCollection of all products.

DataServiceCollection<Products> products =
    new DataServiceCollection<Products>(
        from p in nwsvc.Products
        select p
    );

Example 2: Creating a DataServiceCollection of all products and their associated suppliers.

DataServiceCollection<Products> products =
    new DataServiceCollection<Products>(
        from p in nwsvc.Products.Expand("Suppliers")
        select p
     );

Walkthrough

 

The following is a walkthrough of using data binding in a WPF application.

To get started, you'll want to download all of the required software I use in the walkthrough: 

Step 1: Create an ADO.NET Data Service

Create a new Web Application (named DatabindingDemo):

clip_image012

Our first data access related task is to generate the Entity Framework-based data access layer to the Northwind database.  Right click the ASP.NET project and select 'Add New Item', then select 'ADO.NET Entity Data Model'.  Name the new item nw.edmx:

clip_image014

After clicking ‘Add’ on the screen above, a wizard will open to walk you through creating the Entity Data Model for the Northwind database. Use the default settings until you get to the point where you choose the database objects to include in the model. For this demo, choose only the Products and Suppliers tables.

clip_image016

Once you reach the ‘Choose Your Database Objects’ screen, select the two tables and click ‘Finish’. This will open the Entity Data Model designer view.  This view allows you to customize the auto-generated conceptual data model. To learn more about the mapping capabilities of the Entity Framework, see the MSDN page here.

clip_image018

Create an  ADO.NET Data Service over this model. To create the data service, right click the ASP.NET project and select 'Add New Item'.  Add an 'ADO.NET Data Service’ item called nw.svc

image

This will generate a file (nw.svc.cs) which represents the skeleton of a data service. All we need to do now is point the data service at the data model to be exposed as a REST-service and we’ll be set. The snippet below shows the edits you need to do. One thing to note is that a data service is locked down by default, so we need to take explicit steps to open access to it. For this simple application we’ll enable read and write access to the entire model quickly using the call to ‘SetEntitySetAccessRule’ shown below.

public class nw : DataService< NorthwindEntities >
{
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
    {
        // TODO: set rules to indicate which entity sets and
        //service operations are visible, updatable, etc.
        // Examples:
        config.SetEntitySetAccessRule("*", EntitySetRights.All);
        config.SetServiceOperationAccessRule("*",
            ServiceOperationRights.All);
    }
}

The data service is now created. To test this, run the project and navigate to the nw.svc file. You should see a listing as shown below that outlines all the entry points to the data service. If you don’t, tweak your IE settings and reload.

clip_image024

Step 2: Enable data binding on the client.

By default, the client side types generated by ADO.NET Data Services in Visual Studio 2008 do not implement binding interfaces. To get client side types that do implement the binding interfaces, you have to tell the code generation library that you want client code that has binding enabled. To do this, set an environment variable before starting Visual Studio and then use Add Service Reference (ASR) to generate client proxy code. The environment variable to set is:

set dscodegen_usedsc=1

Note: The use of this environment variable is further explained by the video embedded in this blog post.

Note: It is also possible to generate proxy code that have binding enabled using DataSvcUtil.exe with the /DataServiceCollection and /Version flags.

DataSvcUtil

Step 3: Create client proxy code with binding enabled.

After setting the environment variable in step 2, open the solution you created in step 1 and create a new WPF project.

clip_image028

Once you have created a WPF client project, the next step is to generate client side types. To do this, find the DatabindingClient project in the solution explorer, right-click the project and select Add Service Reference.. .In the Add Service Reference dialog, click the Discover button. The nw.svc service will show up in the Service window. Enter NorthwindService as the Namespace value and select OK. This wizard will generate a set of client side types that can be used to interact with the service created in step 1.

clip_image030

If this step is done correctly, you will see a new NorthwindService node under the Service References Node in the solution explorer.

image

The next step is to create a new instance of the ADO.NET Data Services client context and connect to the service created in step 1. To do this, add the following code to the Window1.xaml.cs file to create a connection to the service; making sure to replace the host and port number with the values for your service.

public partial class Window1 : Window
{
    NorthwindEntities nwsvc = new NorthwindEntities(
            new Uri("
http://localhost:60214/nw.svc"));

    public Window1()
    {
        InitializeComponent();
    }
}

The next step is to create an interface that you can bind the result of a query to. The service you created in step 1 exposes a set of Suppliers and a set of Products from the Northwind database with a one-to-many relationship between them. The XAML code below will create two listviews, one to display the suppliers and another to display the products associated with the current supplier selected in the first view. This type of binding is called master-detail binding.

The code below uses standard WPF binding semantics. The ItemsSource of the supplierView is set to “{Binding}”, this will cause the listview to bind to the collection of items that are supplied as the data context of the supplierView; in this case the collection of items will be a collection of supplier objects. The columns of the supplierView are each bound to a property of the supplier object through the DisplayMemberBinding="{Binding Path=SupplierID}"/> tag.

The second listview, productsView, is bound to the Products property of the supplier objects by the ItemsSource="{Binding Products}" tag.

By supplying the IsSynchronizedWithCurrentItem="True" tag on the listview, you are taking advantage of the feature WPF has to automatically display the items in the second list view (products) that are associated with the currently selected item in the first list view (suppliers).

Paste the following code snippet into the window1.xaml file:

 

   1: <Grid Name="productViewGrid">
   2:     <ListView ItemsSource="{Binding}" Margin="25,11,33,145" Name="supplierView" IsSynchronizedWithCurrentItem="True">
   3:         <ListView.View>
   4:             <GridView>
   5:                 <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Path=SupplierID}"/>
   6:                 <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=CompanyName}"/>
   7:                 <GridViewColumn Header="Address" DisplayMemberBinding="{Binding Path=Address}"/>
   8:                 <GridViewColumn Header="City" DisplayMemberBinding="{Binding Path=City}"/>
   9:                 <GridViewColumn Header="Region" DisplayMemberBinding="{Binding Path=Region}"/>
  10:             </GridView>
  11:         </ListView.View>
  12:     </ListView>
  13:     <ListView Margin="25,0,33,12" Name="productsView" ItemsSource="{Binding Products}" IsSynchronizedWithCurrentItem="True" Height="117" VerticalAlignment="Bottom" >
  14:         <ListView.View>
  15:             <GridView>
  16:                 <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ProductID}"/>
  17:                 <GridViewColumn Header="Name" DisplayMemberBinding="{Binding ProductName}"/>
  18:                 <GridViewColumn Header="QuantityPerUnit" DisplayMemberBinding="{Binding QuantityPerUnit}"/>
  19:                 <GridViewColumn Header="Price" DisplayMemberBinding="{Binding UnitPrice}"/>
  20:                 <GridViewColumn Header="InStock" DisplayMemberBinding="{Binding UnitsInStock}"/>
  21:             </GridView>
  22:         </ListView.View>
  23:     </ListView>
  24: </Grid>

Edit the following attributes of your window: Height="400" Width="600" to properly display the controls.

This will create a WPF interface that looks like this:

clip_image036

The final step to enable binding to these WPF controls is to set the DataContext of the grid in the window you just created to the result of a query for suppliers from the service created in step 1. This is done by executing a standard ADO.NET Data Services query on the context for the set of suppliers and then loading the result of the query into a DataServiceCollection. To do this, add the following code to the constructor for the window:

public Window1()
{
    InitializeComponent();
    this.productViewGrid.DataContext =
        new DataServiceCollection<Suppliers>(
                   nwsvc.Suppliers.Expand("Products")
                );
}

Once this is complete, compile the project and run it. The result should be:

clip_image040

Step 4: Two-way Binding

Up to this point in the walkthrough, you have set up a service, created a WPF client and bound the result of a query to the service to a pair of listview controls in the client. This type of binding you have done so far has all been one-way binding. The DataServiceCollection you used at the end of step 3 also supports two-way binding. This means that any changes made to the collection or items in the collection will propagate to the service when a call to SaveChanges() is made on the context.

This final step will walk you through adding buttons that will add items to the collection of products and take advantage of two-way binding to have those changes propagate to the service and the backing northwind database.

To start, add the following XAML code to the window1.xaml file to create buttons to that will add a product from the list of products and save the changes to the service.

   1: <Button Height="24" HorizontalAlignment="Right" Margin="0,0,89,4" 
   2:     Name="addButton" VerticalAlignment="Bottom" Width="28" 
   3:     Click="addButton_Click">+</Button>
   4: <Button Height="24" HorizontalAlignment="Right" Margin="0,0,33,4" 
   5:     Name="saveButton" VerticalAlignment="Bottom" Width="50" 
   6:     Click="saveButton_Click">Save</Button>

The next step is to handle the click events on the new buttons and add the currently select product in the list. The first thing we will need is a new product window to input the property values of a new product when one is created. To do this, create a new WPF window in your client project called ProductWindow.

image

After creating the window, we need to set up the product window to bind to a single instance of the product class. To configure binding in the product window, you will use the same WPF binding method you used for the supplier window, except this window will bind to a single object and not a collection of objects. Add the following XAML code into the ProductWindow.xaml:

   1: <Grid x:Name="productGrid"> 
   2:     <Grid.ColumnDefinitions> 
   3:         <ColumnDefinition Width="171*" /> 
   4:         <ColumnDefinition Width="159*" /> 
   5:     </Grid.ColumnDefinitions> 
   6:     <Label Height="26" Margin="12,17,68,0" 
   7:         Name="nameLabel" VerticalAlignment="Top">Name:</Label> 
   8:     <Label Margin="12,49,6,0" Name="quantityLabel" Height="26" 
   9:         VerticalAlignment="Top">Quantity Per Unit:</Label> 
  10:     <Label Margin="12,78,68,64" 
  11:         Name="priceLabel">Price:</Label> 
  12:     <Label Height="26" Margin="12,0,68,35" Name="inStockLabel" 
  13:         VerticalAlignment="Bottom">InStock:</Label> 
  14:     <TextBox Height="23" Margin="0,23,28.018,0" Name="nameTextBox" 
  15:         VerticalAlignment="Top" Text="{Binding ProductName}" 
  16:         Grid.Column="1" /> 
  17:     <TextBox Margin="0,52,28.018,0" Name="quantityTextBox" 
  18:         Text="{Binding QuantityPerUnit}" Height="23" 
  19:         VerticalAlignment="Top" Grid.Column="1" /> 
  20:     <TextBox Margin="0,81,28.018,64" Name="priceTextBox" 
  21:         Text="{Binding UnitPrice}" Grid.Column="1" /> 
  22:     <TextBox Height="23" Margin="0,0,28.018,35" 
  23:         Name="inStockTextBox" VerticalAlignment="Bottom" 
  24:         Text="{Binding UnitsInStock}" Grid.Column="1" /> 
  25:     <Button Height="23" Margin="19.018,0,61,6" Name="okButton" 
  26:         VerticalAlignment="Bottom" Grid.Column="1" 
  27:         Click="okButton_Click">OK</Button> 
  28: </Grid>

Set the height of the product window to 206 and the width to 296. Next add the following code to the ProductWindow.xaml.cs file to set the data context to a single product and handle the ok button click event. The click event will add the newly created product to the current suppliers list of products.

public partial class ProductWindow : Window
{
    Suppliers curSupplier;
    Products newProduct;
    public ProductWindow(Products p, Suppliers s)
    {
        InitializeComponent();
        this.productGrid.DataContext = p;
        curSupplier = s;
        newProduct = p;
    }
    private void okButton_Click(object sender,
        RoutedEventArgs e)
    {
        curSupplier.Products.Add(newProduct);
        this.Close();
    }
}

The final step is to handle the add and save button click events in the supplier window. Add the following code to the Window1.xaml.cs file.

Add the following code to the addButton_Click event to create a new product when the add button is selected. The code creates a new Product and creates a new product window for the user to input the property values for the new product .

private void addButton_Click(object sender, RoutedEventArgs e)
{
    Suppliers supplier = this.supplierView.SelectedItem as Suppliers;
    Products product = new Products();
    ProductWindow win = new ProductWindow(product, supplier);
    win.Show();
}

Add the following code to handle the save button click. This button calls SaveChanges on the context which will cause any operations that have been performed on the context to be sent to the service.

private void saveButton_Click(object sender, RoutedEventArgs e)
{
    nwsvc.SaveChanges();
}

Your project is now complete. You can run the form and use the buttons to add items from the collection of products. When you make a change you then click the save button to persist the changes to the service.

More Information

Providing Feedback

The forum intended for questions on all current versions of ADO.NET Data Services is available at: (http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataservices/threads/ )

I look forward to hearing your feedback.

Shayne Burgess

Program Manager, Data Services