How to: Customize Data Binding Behaviors (ADO.NET Data Services)
Note
This topic describes new functionality in ADO.NET Data Services that is available as an update to the .NET Framework version 3.5 Service Pack 1. You can download and install the update from the Microsoft Download Center.
With ADO.NET Data Services, you can supply custom logic that is called by the DataServiceCollection when an object is added or removed from the binding collection or when a property change is detected. This custom logic is provided as methods, referenced as Func delegates, that return a value of false when the default behavior should still be performed when the custom method completes and true when subsequent processing of the event should be stopped.
The examples in this topic supply custom methods for both the entityChanged and entityCollectionChanged parameters of DataServiceCollection. 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 ADO.NET Data Services quickstart.
Example
The following code-behind page for the XAML file creates a DataServiceCollection with custom methods that are called when changes occur to data that is bound to the binding collection. When the CollectionChanged() event occurs, the supplied method prevents an item that has been removed from the binding collection from being deleted from the data service. When the PropertyChanged() event occurs, the ShipDate value is validated to ensure that changes are not made to orders that have already shipped.
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Navigation
Imports System.Windows.Shapes
Imports System.Data.Services.Client
Imports NorthwindClient.NorthwindModel
Imports System.Collections.Specialized
Partial Public Class CustomerOrdersCustom
Inherits Window
Private context As NorthwindEntities
Private trackedCustomers As DataServiceCollection(Of Customers)
Private Const customerCountry As String = "Germany"
Private Const svcUri As String = "https://localhost:12345/Northwind.svc/"
Private Sub Window_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
Try
' 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 Customers)(customerQuery, _
TrackingMode.AutoChangeTracking, "Customers", _
AddressOf OnMyPropertyChanged, AddressOf OnMyCollectionChanged)
' Bind the root StackPanel element to the collection
' related object binding paths are defined in the XAML.
Me.LayoutRoot.DataContext = trackedCustomers
Me.LayoutRoot.UpdateLayout()
Catch ex As DataServiceQueryException
MessageBox.Show("The query could not be completed:\n" + ex.ToString())
Catch ex As InvalidOperationException
MessageBox.Show("The following error occured:\n" + ex.ToString())
End Try
End Sub
' Method that is called when the CollectionChanged event is handled.
Private Function OnMyCollectionChanged( _
ByVal entityCollectionChangedinfo As EntityCollectionChangedParams) As Boolean
If entityCollectionChangedinfo.Action = _
NotifyCollectionChangedAction.Remove Then
' Delete the related items when an order is deleted.
If entityCollectionChangedinfo.TargetEntity.GetType() Is GetType(Orders) Then
' Get the context and object from the supplied parameter.
Dim context = entityCollectionChangedinfo.Context
Dim deletedOrder As Orders = _
CType(entityCollectionChangedinfo.TargetEntity, Orders)
' Load the related OrderDetails.
context.LoadProperty(deletedOrder, "Order_Details")
' Delete the order and its related items
For Each item As Order_Details In deletedOrder.Order_Details
'context.DeleteLink(deletedOrder, "Order_Details", item)
context.DeleteObject(item)
Next
' Delete the order and then return false since the object is already deleted.
context.DeleteObject(deletedOrder)
Return False
Else
Return True
End If
Else
' Use the default behavior.
Return True
End If
End Function
' Method that is called when the PropertyChanged event is handled.
Private Function OnMyPropertyChanged( _
ByVal entityChangedInfo As EntityChangedParams) As Boolean
' Validate a changed order to ensure that changes are not made
' after the order ships.
If entityChangedInfo.Entity.GetType() Is GetType(Orders) AndAlso _
(CType(entityChangedInfo.Entity, Orders).ShippedDate < DateTime.Today) Then
Throw New ApplicationException(String.Format( _
"The order {0} cannot be changed because it shipped on {1}.", _
CType(entityChangedInfo.Entity, Orders).OrderID, _
CType(entityChangedInfo.Entity, Orders).ShippedDate))
Return True
End If
End Function
Private Sub deleteButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
' Get the Orders binding collection.
Dim trackedOrders As DataServiceCollection(Of Orders) = _
(CType(customerIDComboBox.SelectedItem, Customers)).Orders
' Remove the currently selected order.
trackedOrders.Remove(CType(ordersDataGrid.SelectedItem, Orders))
End Sub
Private Sub saveChangesButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
Try
' Save changes to the data service.
context.SaveChanges()
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
End Class
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Navigation
Imports System.Windows.Shapes
Imports System.Data.Services.Client
Imports NorthwindClient.NorthwindModel
Imports System.Collections.Specialized
Partial Public Class CustomerOrdersCustom
Inherits Window
Private context As NorthwindEntities
Private trackedCustomers As DataServiceCollection(Of Customers)
Private Const customerCountry As String = "Germany"
Private Const svcUri As String = "https://localhost:12345/Northwind.svc/"
Private Sub Window_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
Try
' 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 Customers)(customerQuery, _
TrackingMode.AutoChangeTracking, "Customers", _
AddressOf OnMyPropertyChanged, AddressOf OnMyCollectionChanged)
' Bind the root StackPanel element to the collection
' related object binding paths are defined in the XAML.
Me.LayoutRoot.DataContext = 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 occured:\n" + ex.ToString())
End Try
End Sub
' Method that is called when the CollectionChanged event is handled.
Private Function OnMyCollectionChanged( _
ByVal entityCollectionChangedinfo As EntityCollectionChangedParams) As Boolean
If entityCollectionChangedinfo.Action = _
NotifyCollectionChangedAction.Remove Then
' Delete the related items when an order is deleted.
If entityCollectionChangedinfo.TargetEntity.GetType() Is GetType(Orders) Then
' Get the context and object from the supplied parameter.
Dim context = entityCollectionChangedinfo.Context
Dim deletedOrder As Orders = _
CType(entityCollectionChangedinfo.TargetEntity, Orders)
If deletedOrder.Order_Details.Count = 0 Then
' Load the related OrderDetails.
context.LoadProperty(deletedOrder, "Order_Details")
End If
' Delete the order and its related items
For Each item As Order_Details In deletedOrder.Order_Details
'context.DeleteLink(deletedOrder, "Order_Details", item)
context.DeleteObject(item)
Next
' Delete the order and then return false since the object is already deleted.
context.DeleteObject(deletedOrder)
Return True
Else
Return False
End If
Else
' Use the default behavior.
Return False
End If
End Function
' Method that is called when the PropertyChanged event is handled.
Private Function OnMyPropertyChanged( _
ByVal entityChangedInfo As EntityChangedParams) As Boolean
' Validate a changed order to ensure that changes are not made
' after the order ships.
If entityChangedInfo.Entity.GetType() Is GetType(Orders) AndAlso _
(CType(entityChangedInfo.Entity, Orders).ShippedDate < DateTime.Today) Then
Throw New ApplicationException(String.Format( _
"The order {0} cannot be changed because it shipped on {1}.", _
CType(entityChangedInfo.Entity, Orders).OrderID, _
CType(entityChangedInfo.Entity, Orders).ShippedDate))
Return False
End If
End Function
Private Sub deleteButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
If customerIDComboBox.SelectedItem IsNot Nothing Then
' Get the Orders binding collection.
Dim trackedOrders As DataServiceCollection(Of Orders) = _
(CType(customerIDComboBox.SelectedItem, Customers)).Orders
' Remove the currently selected order.
trackedOrders.Remove(CType(ordersDataGrid.SelectedItem, Orders))
End If
End Sub
Private Sub saveChangesButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
Try
' Save changes to the data service.
context.SaveChanges()
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.Services.Client;
using NorthwindModel;
using System.Collections.Specialized;
namespace NorthwindClient
{
public partial class CustomerOrdersCustom : Window
{
private NorthwindEntities context;
private DataServiceCollection<Customers> trackedCustomers;
private const string customerCountry = "Germany";
private const string svcUri = "https://localhost:12345/Northwind.svc/";
public CustomerOrdersCustom()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
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<Customers>(customerQuery,
TrackingMode.AutoChangeTracking,"Customers",
OnPropertyChanged, OnCollectionChanged);
// Bind the root StackPanel element to the collection;
// related object binding paths are defined in the XAML.
this.LayoutRoot.DataContext = trackedCustomers;
}
catch (DataServiceQueryException ex)
{
MessageBox.Show("The query could not be completed:\n" + ex.ToString());
}
catch (InvalidOperationException ex)
{
MessageBox.Show("The following error occured:\n" + ex.ToString());
}
}
// Method that is called when the CollectionChanged event is handled.
private bool OnCollectionChanged(
EntityCollectionChangedParams entityCollectionChangedinfo)
{
if (entityCollectionChangedinfo.Action ==
NotifyCollectionChangedAction.Remove)
{
// Delete the related items when an order is deleted.
if (entityCollectionChangedinfo.TargetEntity.GetType() == typeof(Orders))
{
// Get the context and object from the supplied parameter.
DataServiceContext context = entityCollectionChangedinfo.Context;
Orders deletedOrder = entityCollectionChangedinfo.TargetEntity as Orders;
if (deletedOrder.Order_Details.Count == 0)
{
// Load the related OrderDetails.
context.LoadProperty(deletedOrder, "Order_Details");
}
// Delete the order and its related items;
foreach (Order_Details item in deletedOrder.Order_Details)
{
//context.DeleteLink(deletedOrder, "Order_Details", item);
context.DeleteObject(item);
}
// Delete the order and then return false since the object is already deleted.
context.DeleteObject(deletedOrder);
return true;
}
else
{
return false;
}
}
else
{
// Use the default behavior.
return false;
}
}
// Method that is called when the PropertyChanged event is handled.
private bool OnPropertyChanged(EntityChangedParams entityChangedInfo)
{
// Validate a changed order to ensure that changes are not made
// after the order ships.
if ((entityChangedInfo.Entity.GetType() == typeof(Orders)) &&
((Orders)(entityChangedInfo.Entity)).ShippedDate < DateTime.Today)
{
throw new ApplicationException(string.Format(
"The order {0} cannot be changed because it shipped on {1}.",
((Orders)(entityChangedInfo.Entity)).OrderID,
((Orders)(entityChangedInfo.Entity)).ShippedDate));
}
return false;
}
private void deleteButton_Click(object sender, RoutedEventArgs e)
{
if (customerIDComboBox.SelectedItem != null)
{
// Get the Orders binding collection.
DataServiceCollection<Orders> trackedOrders =
((Customers)(customerIDComboBox.SelectedItem)).Orders;
// Remove the currently selected order.
trackedOrders.Remove((Orders)(ordersDataGrid.SelectedItem));
}
}
private void saveChangesButton_Click(object sender, RoutedEventArgs e)
{
try
{
// Save changes to the data service.
context.SaveChanges();
}
catch (DataServiceClientException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
The following XAML defines the window for the previous example.
<Window x:Class="NorthwindClient.CustomerOrdersCustom"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
Height="423" Width="679" Loaded="Window_Loaded" >
<StackPanel Orientation="Vertical" Height="Auto" Name="LayoutRoot" Width="Auto">
<Label Content="Customer ID" Margin="20,0,0,0" />
<ComboBox Name="customerIDComboBox" DisplayMemberPath="CustomerID" ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="True" SelectedIndex="0" Height="23" Width="120"
HorizontalAlignment="Left" Margin="20,0,0,0" VerticalAlignment="Center" />
<ListView ItemsSource="{Binding Path=Orders}" Name="ordersDataGrid" Margin="34,46,34,50">
<ListView.View>
<GridView AllowsColumnReorder="False" ColumnHeaderToolTip="Line Items">
<GridViewColumn DisplayMemberBinding="{Binding Path=OrderID, Mode=OneWay}"
Header="Order ID" Width="50"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=OrderDate, Mode=TwoWay}"
Header="Order Date" Width="50"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Freight, Mode=TwoWay}"
Header="Freight Cost" Width="50"/>
</GridView>
</ListView.View>
</ListView>
<StackPanel Orientation="Horizontal">
<Button Name="deleteButton" Content="Delete Order" Click="deleteButton_Click"
Width="80" Height="30" Margin="450,0,10,0"/>
<Button Name="saveChangesButton" Content="Save Changes" Click="saveChangesButton_Click"
Width="80" Height="30" Margin="10,0,0,0"/>
</StackPanel>
</StackPanel>
</Window>
See Also
Other Resources
Using a Data Service in a .NET Framework Application (ADO.NET Data Services)