EntityCollectionChangedParams 類別

定義

總結了代表的 CollectionChanged 論點。

public ref class EntityCollectionChangedParams sealed
public sealed class EntityCollectionChangedParams
type EntityCollectionChangedParams = class
Public NotInheritable Class EntityCollectionChangedParams
繼承
EntityCollectionChangedParams

範例

以下 XAML 檔案的程式碼說明頁面會建立 DataServiceCollection<T> 一個自訂方法,當綁定到綁定集合的資料發生變更時會被呼叫。 當事件 CollectionChanged 發生時,所提供的方法是防止已從綁定集合中移除的項目從資料服務中被刪除。 事件發生時 PropertyChangedShipDate 會驗證該數值,以確保不會對已出貨的訂單進行更改。

using System;
using System.Collections.Specialized;
using System.Data.Services.Client;
using System.Linq;
using System.Windows;
using NorthwindClient.Northwind;

namespace NorthwindClient
{
    public partial class CustomerOrdersCustom : Window
    {
        private NorthwindEntities context;
        private DataServiceCollection<Customer> trackedCustomers;
        private const string customerCountry = "Germany";
        private const string svcUri = "http://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<Customer>(customerQuery,
                    TrackingMode.AutoChangeTracking,"Customers",
                    OnPropertyChanged, OnCollectionChanged);

                // 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());
            }
        }

        // 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(Order))
                {
                    // Get the context and object from the supplied parameter.
                    DataServiceContext context = entityCollectionChangedinfo.Context;
                    Order deletedOrder = entityCollectionChangedinfo.TargetEntity as Order;

                    if (deletedOrder.Order_Details.Count == 0)
                    {
                        // Load the related OrderDetails.
                        context.LoadProperty(deletedOrder, "Order_Details");
                    }

                    // Delete the order and its related items;
                    foreach (Order_Detail item in deletedOrder.Order_Details)
                    {
                        context.DeleteObject(item);
                    }

                    // Delete the order and then return true 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(Order)) &&
                ((Order)(entityChangedInfo.Entity)).ShippedDate < DateTime.Today)
            {
                throw new ApplicationException(string.Format(
                    "The order {0} cannot be changed because it shipped on {1}.",
                    ((Order)(entityChangedInfo.Entity)).OrderID,
                    ((Order)(entityChangedInfo.Entity)).ShippedDate));
            }
            return false;
        }

        private void deleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (customerIDComboBox.SelectedItem != null)
            {
                // Get the Orders binding collection.
                DataServiceCollection<Order> trackedOrders =
                    ((Customer)(customerIDComboBox.SelectedItem)).Orders;

                // Remove the currently selected order.
                trackedOrders.Remove((Order)(ordersDataGrid.SelectedItem));
            }
        }

        private void saveChangesButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Save changes to the data service.
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
Imports System.Collections.Specialized
Imports System.Data.Services.Client
Imports System.Windows
Imports northwindclientvb.Northwind

Partial Public Class CustomerOrdersCustom
    Inherits Window
    Private context As NorthwindEntities
    'Private trackedCustomers As DataServiceCollection(Of Customer)
    '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))

    '        '<snippetMasterDetailBinding>
    '        ' 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,
    '                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
    '        '</snippetMasterDetailBinding>
    '    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

    ' 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(Order) Then

    '            ' Get the context and object from the supplied parameter.
    '            Dim context = entityCollectionChangedinfo.Context
    '            Dim deletedOrder As Order = _
    '            CType(entityCollectionChangedinfo.TargetEntity, Order)

    '            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_Detail In deletedOrder.Order_Details
    '                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(Order) AndAlso
    '        (CType(entityChangedInfo.Entity, Order).ShippedDate < DateTime.Today) Then
    '        Throw New ApplicationException(String.Format(
    '            "The order {0} cannot be changed because it shipped on {1}.",
    '            CType(entityChangedInfo.Entity, Order).OrderID,
    '            CType(entityChangedInfo.Entity, Order).ShippedDate))
    '        Return False
    '    Else
    '        Return True
    '    End If
    'End Function

    'Private Sub deleteButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    '    ' Get the Orders binding collection.
    '    If customerIDComboBox.SelectedItem IsNot Nothing Then
    '        Dim trackedOrders As DataServiceCollection(Of Order) = _
    '            (CType(customerIDComboBox.SelectedItem, Customer)).Orders

    '        ' Remove the currently selected order.
    '        trackedOrders.Remove(CType(ordersDataGrid.SelectedItem, Order))
    '    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
Imports System.Collections.Specialized
Imports System.Data.Services.Client
Imports System.Linq
Imports System.Windows
Imports northwindclientvb.Northwind
Imports northwindclientvb.NorthwindModel

Partial Public Class CustomerOrdersCustom
    Inherits Window
    Private _context As Northwind.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 Northwind.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,
                    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 occurred:\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))
        End If
        Return True
    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

以下 XAML 程式碼定義了前一個範例的視窗。

<Window x:Class="CustomerOrdersCustom"
             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>
        <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>

屬性

名稱 Description
Action

一個 NotifyCollectionChangedAction 表示集合如何變更的數值。

Collection

DataServiceCollection<T> 現在情況已經改變了。

Context

DataServiceContext與之相關的DataServiceCollection<T>情況已經改變。

PropertyName

來源物件上的導航屬性,參考已變更的集合。

SourceEntity

來源物件透過導覽屬性參考集合中的目標物件。

SourceEntitySet

來源物件的實體集合。

TargetEntity

集合中已變更的實體物件。

TargetEntitySet

集合中物件的實體集合名稱。

方法

名稱 Description
Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設哈希函式。

(繼承來源 Object)
GetType()

取得目前實例的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
ToString()

傳回表示目前 物件的字串。

(繼承來源 Object)

適用於

另請參閱