Udostępnij za pośrednictwem


DataServiceCollection<T> Class

Represents a dynamic entity collection that provides notifications when items get added, removed, or when the list is refreshed.

Inheritance Hierarchy

System.Object
  System.Collections.ObjectModel.Collection<T>
    System.Collections.ObjectModel.ObservableCollection<T>
      System.Data.Services.Client.DataServiceCollection<T>

Namespace:  System.Data.Services.Client
Assembly:  Microsoft.Data.Services.Client (in Microsoft.Data.Services.Client.dll)

Syntax

'Declaration
Public Class DataServiceCollection(Of T) _
    Inherits ObservableCollection(Of T)
'Usage
Dim instance As DataServiceCollection(Of T)
public class DataServiceCollection<T> : ObservableCollection<T>
generic<typename T>
public ref class DataServiceCollection : public ObservableCollection<T>
type DataServiceCollection<'T> =  
    class 
        inherit ObservableCollection<'T>
    end
JScript does not support generic types and methods.

Type Parameters

  • T
    An entity type.

The DataServiceCollection<T> type exposes the following members.

Constructors

  Name Description
Public method DataServiceCollection<T>() Initializes a new instance of the DataServiceCollection<T> class.
Public method DataServiceCollection<T>(IEnumerable<T>) Initializes a new instance of the DataServiceCollection<T> class based on query execution.
Public method DataServiceCollection<T>(DataServiceContext) Initializes a new instance of the DataServiceCollection<T> class that uses the specified DataServiceContext.
Public method DataServiceCollection<T>(IEnumerable<T>, TrackingMode) Initializes a new instance of the DataServiceCollection<T> class based on query execution and with the specified tracking mode.
Public method DataServiceCollection<T>(DataServiceContext, String, Func<EntityChangedParams, Boolean>, Func<EntityCollectionChangedParams, Boolean>) Initializes a new instance of the DataServiceCollection<T> class with the supplied change method delegates and that uses the specified DataServiceContext.
Public method DataServiceCollection<T>(IEnumerable<T>, TrackingMode, String, Func<EntityChangedParams, Boolean>, Func<EntityCollectionChangedParams, Boolean>) Initializes a new instance of the DataServiceCollection<T> class based on query execution and with the supplied change method delegates.
Public method DataServiceCollection<T>(DataServiceContext, IEnumerable<T>, TrackingMode, String, Func<EntityChangedParams, Boolean>, Func<EntityCollectionChangedParams, Boolean>) Initializes a new instance of the DataServiceCollection<T> class based on query execution, with the supplied change method delegates, and that uses the supplied DataServiceContext.

Top

Properties

  Name Description
Public property Continuation Gets a continuation object that is used to return the next set of paged results.
Public property Count (Inherited from Collection<T>.)
Public property Item (Inherited from Collection<T>.)
Protected property Items (Inherited from Collection<T>.)

Top

Methods

  Name Description
Public method Add (Inherited from Collection<T>.)
Protected method BlockReentrancy (Inherited from ObservableCollection<T>.)
Public method CancelAsyncLoad
Protected method CheckReentrancy (Inherited from ObservableCollection<T>.)
Public method Clear() (Inherited from Collection<T>.)
Public method Clear(Boolean) Indicates whether all the items from the collection are removed.
Protected method ClearItems (Inherited from ObservableCollection<T>.)
Public method Contains (Inherited from Collection<T>.)
Public method CopyTo (Inherited from Collection<T>.)
Public method Detach Disables the DataServiceContext tracking of all items in the collection.
Public method Equals (Inherited from Object.)
Protected method Finalize (Inherited from Object.)
Public method GetEnumerator (Inherited from Collection<T>.)
Public method GetHashCode (Inherited from Object.)
Public method GetType (Inherited from Object.)
Public method IndexOf (Inherited from Collection<T>.)
Public method Insert (Inherited from Collection<T>.)
Protected method InsertItem Adds a specified item to the collection at the specified index. (Overrides ObservableCollection<T>.InsertItem(Int32, T).)
Public method Load(IEnumerable<T>) Loads a collection of entity objects into the collection.Not supported by the WCF Data Services 5.0 client for Silverlight.
Public method Load(T) Loads a single entity object into the collection.Not supported by the WCF Data Services 5.0 client for Silverlight.
Public method LoadAsync() Asynchronously loads items into the collection, when it represents the navigation property of an entity.Supported only by the WCF Data Services 5.0 client for Silverlight.
Public method LoadAsync(IQueryable<T>) Asynchronously loads the collection by executing a DataServiceQuery<TElement>.Supported only by the WCF Data Services 5.0 client for Silverlight.
Public method LoadAsync(Uri)
Public method LoadNextPartialSetAsync Loads the next page of data into the collection.Supported only by the WCF Data Services 5.0 client for Silverlight.
Protected method MemberwiseClone (Inherited from Object.)
Public method Move (Inherited from ObservableCollection<T>.)
Protected method MoveItem (Inherited from ObservableCollection<T>.)
Protected method OnCollectionChanged (Inherited from ObservableCollection<T>.)
Protected method OnPropertyChanged (Inherited from ObservableCollection<T>.)
Public method Remove (Inherited from Collection<T>.)
Public method RemoveAt (Inherited from Collection<T>.)
Protected method RemoveItem (Inherited from ObservableCollection<T>.)
Protected method SetItem (Inherited from ObservableCollection<T>.)
Public method ToString (Inherited from Object.)

Top

Events

  Name Description
Public event CollectionChanged (Inherited from ObservableCollection<T>.)
Public event LoadCompleted Occurs when an asynchronous load operation completes.Supported only by the WCF Data Services 5.0 client for Silverlight.
Protected event PropertyChanged (Inherited from ObservableCollection<T>.)

Top

Explicit Interface Implementations

  Name Description
Explicit interface implemetationPrivate method IList.Add (Inherited from Collection<T>.)
Explicit interface implemetationPrivate method IList.Contains (Inherited from Collection<T>.)
Explicit interface implemetationPrivate method ICollection.CopyTo (Inherited from Collection<T>.)
Explicit interface implemetationPrivate method IEnumerable.GetEnumerator (Inherited from Collection<T>.)
Explicit interface implemetationPrivate method IList.IndexOf (Inherited from Collection<T>.)
Explicit interface implemetationPrivate method IList.Insert (Inherited from Collection<T>.)
Explicit interface implemetationPrivate property IList.IsFixedSize (Inherited from Collection<T>.)
Explicit interface implemetationPrivate property ICollection<T>.IsReadOnly (Inherited from Collection<T>.)
Explicit interface implemetationPrivate property IList.IsReadOnly (Inherited from Collection<T>.)
Explicit interface implemetationPrivate property ICollection.IsSynchronized (Inherited from Collection<T>.)
Explicit interface implemetationPrivate property IList.Item (Inherited from Collection<T>.)
Explicit interface implemetationPrivate event INotifyPropertyChanged.PropertyChanged (Inherited from ObservableCollection<T>.)
Explicit interface implemetationPrivate method IList.Remove (Inherited from Collection<T>.)
Explicit interface implemetationPrivate property ICollection.SyncRoot (Inherited from Collection<T>.)

Top

Remarks

WCF Data Services provides the DataServiceCollection<T> class to support binding data to controls in client applications. This class inherits from the ObservableCollection<T> class, which implements the INotifyCollectionChanged interface and is the primary data binding mechanism for Windows Presentation Foundation (WPF) and Silverlight-based applications.

You can load an ObservableCollection<T> binding collection by using any collection that implements the IEnumerable<T> interface. Items loaded into the binding collection must implement the INotifyPropertyChanged interface. For more information, see Binding Data to Controls (WCF Data Services).

Examples

The following example is from the code-behind page for an Extensible Application Markup Language (XAML) page that defines the SalesOrders window in WPF. When the window is loaded, an DataServiceCollection<T> is created based on the result of a query that returns customers with related objects, filtered by country. This result is bound to the DataContext property of the StackPanel that is the root layout control for the WPF window.

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

Partial Public Class CustomerOrdersWpf
    Inherits Window

    Private context As NorthwindEntities
    Private trackedCustomers As DataServiceCollection(Of Customer)
    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 Customer)(customerQuery)

                ' 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 occurred:\n" + ex.ToString())
        End Try
    End Sub
    Private Sub saveChangesButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        ' Save changes to the data service.
        context.SaveChanges()
    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 NorthwindClient.Northwind;

namespace NorthwindClient
{
    public partial class CustomerOrdersWpf : Window
    {
        private NorthwindEntities context;
        private DataServiceCollection<Customer> trackedCustomers;
        private const string customerCountry = "Germany";
        private const string svcUri = "https://localhost:12345/Northwind.svc/";

        public CustomerOrdersWpf()
        {
            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<Customer>(customerQuery);

                // Bind the root StackPanel element to the collection;
                // related object binding paths are defined in the XAML.
                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 occurred:\n" + ex.ToString());
            }
        }
        private void saveChangesButton_Click(object sender, RoutedEventArgs e)
        {
            // Save changes to the data service.
            context.SaveChanges();
        }
    }
}

The following is the XAML that defines the SalesOrders window in WPF for the previous example.

    <Window x:Class="CustomerOrdersWpf"
             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>
        <Button Name="saveChangesButton" Content="Save Changes" Click="saveChangesButton_Click" 
                Width="80" Height="30" Margin="450,0,0,0"/>
    </StackPanel>
</Window>

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

System.Data.Services.Client Namespace

Other Resources

Binding Data to Controls (WCF Data Services)