DataServiceCollection<T> 类

定义

表示一个动态实体集合,在添加项、移除项或刷新列表时,此集合将提供通知。Represents a dynamic entity collection that provides notifications when items get added, removed, or when the list is refreshed.

generic <typename T>
public ref class DataServiceCollection : System::Collections::ObjectModel::ObservableCollection<T>
public class DataServiceCollection<T> : System.Collections.ObjectModel.ObservableCollection<T>
type DataServiceCollection<'T> = class
    inherit ObservableCollection<'T>
Public Class DataServiceCollection(Of T)
Inherits ObservableCollection(Of T)

类型参数

T

一个实体类型。An entity type.

继承
DataServiceCollection<T>

示例

下面的示例摘自在 WPF 中定义 SalesOrders 窗口的可扩展应用程序标记语言 (XAML) 页的代码隐藏页。The following example is from the code-behind page for an Extensible Application Markup Language (XAML) page that defines the SalesOrders window in WPF. 加载窗口时, DataServiceCollection<T>会根据查询结果创建, 该查询返回具有相关对象的客户, 并按国家/地区进行筛选。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/region. 此结果绑定到作为 WPF 窗口的根布局控件的 DataContextStackPanel 属性。This result is bound to the DataContext property of the StackPanel that is the root layout control for the WPF window.

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 = "http://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();
        }
    }
}
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 = "http://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

以下 XAML 在 WPF 中为上一个示例定义 SalesOrders 窗口。The following is the XAML that defines the SalesOrders window in WPF for the previous example.

    <Window x:Class="CustomerOrdersWpf"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://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>

注解

WCF 数据服务WCF Data ServicesDataServiceCollection<T>提供类以支持将数据绑定到客户端应用程序中的控件。provides the DataServiceCollection<T> class to support binding data to controls in client applications. 此类继承自ObservableCollection<T>类, 该类INotifyCollectionChanged实现接口, 是用于 Windows Presentation Foundation (WPF) 和基于 Silverlight 的应用程序的主数据绑定机制。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.

可以通过使用实现了 ObservableCollection<T> 接口的任何集合来加载 IEnumerable<T> 绑定集合。You can load an ObservableCollection<T> binding collection by using any collection that implements the IEnumerable<T> interface. 加载到绑定集合中的项必须实现 INotifyPropertyChanged 接口。Items loaded into the binding collection must implement the INotifyPropertyChanged interface. 有关详细信息, 请参阅将数据绑定到控件For more information, see Binding Data to Controls.

构造函数

DataServiceCollection<T>()

创建 DataServiceCollection<T> 类的新实例。Creates a new instance of the DataServiceCollection<T> class.

DataServiceCollection<T>(DataServiceContext)

创建 DataServiceCollection<T> 类的新实例,该实例使用指定的 DataServiceContextCreates a new instance of the DataServiceCollection<T> class that uses the specified DataServiceContext.

DataServiceCollection<T>(DataServiceContext, IEnumerable<T>, TrackingMode, String, Func<EntityChangedParams,Boolean>, Func<EntityCollectionChangedParams,Boolean>)

根据查询执行并使用提供的更改方法委托创建 DataServiceCollection<T> 类的新实例,该实例使用提供的 DataServiceContextCreates a new instance of the DataServiceCollection<T> class a based on query execution, with the supplied change method delegates, and that uses the supplied DataServiceContext.

DataServiceCollection<T>(DataServiceContext, String, Func<EntityChangedParams,Boolean>, Func<EntityCollectionChangedParams,Boolean>)

使用提供的更改方法委托创建 DataServiceCollection<T> 类的新实例,该实例使用指定的 DataServiceContextCreates a new instance of the DataServiceCollection<T> class with the supplied change method delegates and that uses the specified DataServiceContext.

DataServiceCollection<T>(IEnumerable<T>)

根据查询执行创建 DataServiceCollection<T> 类的新实例。Creates a new instance of the DataServiceCollection<T> class based on query execution.

DataServiceCollection<T>(IEnumerable<T>, TrackingMode)

根据查询执行并使用指定的跟踪模式创建 DataServiceCollection<T> 类的新实例。Creates a new instance of the DataServiceCollection<T> class based on query execution and with the specified tracking mode.

DataServiceCollection<T>(IEnumerable<T>, TrackingMode, String, Func<EntityChangedParams,Boolean>, Func<EntityCollectionChangedParams,Boolean>)

根据查询执行并使用提供的更改方法委托创建 DataServiceCollection<T> 类的新实例。Creates a new instance of the DataServiceCollection<T> class a based on query execution and with the supplied change method delegates.

属性

Continuation

获取用于返回下一分页结果集的延续对象。Gets a continuation object that is used to return the next set of paged results.

Count

获取 Collection<T> 中实际包含的元素数。Gets the number of elements actually contained in the Collection<T>.

(继承自 Collection<T>)
Item[Int32]

获取或设置指定索引处的元素。Gets or sets the element at the specified index.

(继承自 Collection<T>)
Items

获取 IList<T> 周围的 Collection<T> 包装。Gets a IList<T> wrapper around the Collection<T>.

(继承自 Collection<T>)

方法

Add(T)

将对象添加到 Collection<T> 的结尾处。Adds an object to the end of the Collection<T>.

(继承自 Collection<T>)
BlockReentrancy()

不允许可重入的更改此集合的尝试。Disallows reentrant attempts to change this collection.

(继承自 ObservableCollection<T>)
CheckReentrancy()

检查企图更改此集合的可重入尝试。Checks for reentrant attempts to change this collection.

(继承自 ObservableCollection<T>)
Clear()

Collection<T> 中移除所有元素。Removes all elements from the Collection<T>.

(继承自 Collection<T>)
Clear(Boolean)

从集合中移除所有项,也可以选择从 DataServiceContext 中分离所有项。Removes all items from the collection, and optionally detaches all the items from the DataServiceContext.

ClearItems()

从集合中移除所有项。Removes all items from the collection.

(继承自 ObservableCollection<T>)
Contains(T)

确定某元素是否在 Collection<T> 中。Determines whether an element is in the Collection<T>.

(继承自 Collection<T>)
CopyTo(T[], Int32)

从目标数组的指定索引处开始将整个 Collection<T> 复制到兼容的一维 ArrayCopies the entire Collection<T> to a compatible one-dimensional Array, starting at the specified index of the target array.

(继承自 Collection<T>)
Detach()

禁用集合中所有项的 DataServiceContext 跟踪。Disables DataServiceContext tracking of all items in the collection.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetEnumerator()

返回循环访问 Collection<T> 的枚举数。Returns an enumerator that iterates through the Collection<T>.

(继承自 Collection<T>)
GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
IndexOf(T)

搜索指定的对象,并返回整个 Collection<T> 中第一个匹配项的从零开始的索引。Searches for the specified object and returns the zero-based index of the first occurrence within the entire Collection<T>.

(继承自 Collection<T>)
Insert(Int32, T)

将元素插入 Collection<T> 的指定索引处。Inserts an element into the Collection<T> at the specified index.

(继承自 Collection<T>)
InsertItem(Int32, T)

将指定的项添加到集合中的指定索引位置。Adds a specified item to the collection at the specified index.

Load(IEnumerable<T>)

将实体对象的集合加载到集合中。Loads a collection of entity objects into the collection.

Load(T)

将一个实体对象加载到集合中。Loads a single entity object into the collection.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
Move(Int32, Int32)

将指定索引处的项移至集合中的新位置。Moves the item at the specified index to a new location in the collection.

(继承自 ObservableCollection<T>)
MoveItem(Int32, Int32)

将指定索引处的项移至集合中的新位置。Moves the item at the specified index to a new location in the collection.

(继承自 ObservableCollection<T>)
OnCollectionChanged(NotifyCollectionChangedEventArgs)

引发带有提供的参数的 CollectionChanged 事件。Raises the CollectionChanged event with the provided arguments.

(继承自 ObservableCollection<T>)
OnPropertyChanged(PropertyChangedEventArgs)

引发带有提供的参数的 PropertyChanged 事件。Raises the PropertyChanged event with the provided arguments.

(继承自 ObservableCollection<T>)
Remove(T)

Collection<T> 中移除特定对象的第一个匹配项。Removes the first occurrence of a specific object from the Collection<T>.

(继承自 Collection<T>)
RemoveAt(Int32)

移除 Collection<T> 的指定索引处的元素。Removes the element at the specified index of the Collection<T>.

(继承自 Collection<T>)
RemoveItem(Int32)

移除集合中指定索引处的项。Removes the item at the specified index of the collection.

(继承自 ObservableCollection<T>)
SetItem(Int32, T)

替换指定索引处的元素。Replaces the element at the specified index.

(继承自 ObservableCollection<T>)
ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

事件

CollectionChanged

在添加、移除、更改或移动项或者在刷新整个列表时发生。Occurs when an item is added, removed, changed, moved, or the entire list is refreshed.

(继承自 ObservableCollection<T>)
PropertyChanged

在属性值更改时发生。Occurs when a property value changes.

(继承自 ObservableCollection<T>)

显式界面实现

ICollection.CopyTo(Array, Int32)

从特定的 ICollection 索引开始,将 Array 的元素复制到一个 Array 中。Copies the elements of the ICollection to an Array, starting at a particular Array index.

(继承自 Collection<T>)
ICollection.IsSynchronized

获取一个值,该值指示是否同步对 ICollection 的访问(线程安全)。Gets a value indicating whether access to the ICollection is synchronized (thread safe).

(继承自 Collection<T>)
ICollection.SyncRoot

获取可用于同步对 ICollection 的访问的对象。Gets an object that can be used to synchronize access to the ICollection.

(继承自 Collection<T>)
ICollection<T>.IsReadOnly

获取一个值,该值指示 ICollection<T> 是否为只读。Gets a value indicating whether the ICollection<T> is read-only.

(继承自 Collection<T>)
IEnumerable.GetEnumerator()

返回循环访问集合的枚举数。Returns an enumerator that iterates through a collection.

(继承自 Collection<T>)
IList.Add(Object)

将某项添加到 IList 中。Adds an item to the IList.

(继承自 Collection<T>)
IList.Contains(Object)

确定 IList 是否包含特定值。Determines whether the IList contains a specific value.

(继承自 Collection<T>)
IList.IndexOf(Object)

确定 IList 中特定项的索引。Determines the index of a specific item in the IList.

(继承自 Collection<T>)
IList.Insert(Int32, Object)

将某项插入 IList 中指定的索引处。Inserts an item into the IList at the specified index.

(继承自 Collection<T>)
IList.IsFixedSize

获取一个值,该值指示 IList 是否具有固定大小。Gets a value indicating whether the IList has a fixed size.

(继承自 Collection<T>)
IList.IsReadOnly

获取一个值,该值指示 IList 是否为只读。Gets a value indicating whether the IList is read-only.

(继承自 Collection<T>)
IList.Item[Int32]

获取或设置指定索引处的元素。Gets or sets the element at the specified index.

(继承自 Collection<T>)
IList.Remove(Object)

IList 中移除特定对象的第一个匹配项。Removes the first occurrence of a specific object from the IList.

(继承自 Collection<T>)
INotifyPropertyChanged.PropertyChanged

在属性值更改时发生。Occurs when a property value changes.

(继承自 ObservableCollection<T>)

扩展方法

CopyToDataTable<T>(IEnumerable<T>)

在给定其泛型参数 TDataTable 的输入 DataRow 对象的情况下,返回包含 IEnumerable<T> 对象副本的 DataRowReturns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 IEnumerable<T> 对象复制到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 IEnumerable<T> 对象复制到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

Ancestors<T>(IEnumerable<T>)

返回元素集合,其中包含源集合中每个节点的上级。Returns a collection of elements that contains the ancestors of every node in the source collection.

Ancestors<T>(IEnumerable<T>, XName)

返回经过筛选的元素集合,其中包含源集合中每个节点的上级。Returns a filtered collection of elements that contains the ancestors of every node in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

DescendantNodes<T>(IEnumerable<T>)

返回源集合中每个文档和元素的子代节点的集合。Returns a collection of the descendant nodes of every document and element in the source collection.

Descendants<T>(IEnumerable<T>)

返回元素集合,其中包含源集合中每个元素和文档的子代元素。Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

Descendants<T>(IEnumerable<T>, XName)

返回经过筛选的元素集合,其中包含源集合中每个元素和文档的子代元素。Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

Elements<T>(IEnumerable<T>)

返回源集合中每个元素和文档的子元素的集合。Returns a collection of the child elements of every element and document in the source collection.

Elements<T>(IEnumerable<T>, XName)

返回源集合中经过筛选的每个元素和文档的子元素集合。Returns a filtered collection of the child elements of every element and document in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

InDocumentOrder<T>(IEnumerable<T>)

返回节点集合(其中包含源集合中的所有节点),并按文档顺序排列。Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>)

返回源集合中每个文档和元素的子节点集合。Returns a collection of the child nodes of every document and element in the source collection.

Remove<T>(IEnumerable<T>)

将源集合中的每个节点从其父节点中移除。Removes every node in the source collection from its parent node.

适用于

另请参阅