컨트롤에 데이터 바인딩(WCF Data Services)

WCF Data Services 를 사용하면 ComboBox, ListView 등의 컨트롤을 DataServiceCollection 클래스 인스턴스에 바인딩할 수 있습니다. ObservableCollection 클래스에서 상속되는 이 컬렉션에는 Open Data Protocol(OData) 피드의 데이터가 포함됩니다. 이 클래스는 항목이 추가 또는 제거될 때 알림을 제공하는 동적 데이터 컬렉션을 나타냅니다. 데이터 바인딩에 DataServiceCollection 인스턴스를 사용하는 경우 WCF Data Services 클라이언트 라이브러리는 이러한 이벤트를 처리하여 DataServiceContext에 의해 추적되는 개체가 바인딩된 UI 요소의 데이터와 동기화된 상태로 유지되도록 합니다.

DataServiceCollection 클래스는 INotifyCollectionChanged 인터페이스를 간접적으로 구현하여 개체가 컬렉션에 추가 또는 제거된 경우 컨텍스트에 알립니다. DataServiceCollection과 함께 사용된 데이터 서비스 형식 개체는 INotifyPropertyChanged 인터페이스도 구현하여 바인딩 컬렉션의 개체 속성이 변경된 경우 DataServiceCollection에 알려야 합니다.

Ee373844.note(ko-kr,VS.100).gif참고:
서비스 참조 추가 대화 상자나 DataSvcUtil.exe 도구에 /dataservicecollection 옵션을 사용하여 클라이언트 데이터 서비스 클래스를 생성하는 경우 생성된 데이터 클래스는 INotifyPropertyChanged 인터페이스를 구현합니다.자세한 내용은 방법: 수동으로 클라이언트 데이터 서비스 클래스 생성(WCF Data Services)을 참조하십시오.

바인딩 컬렉션 만들기

제공된 DataServiceContext 인스턴스와 선택적으로 실행 시 IEnumerable 인스턴스를 반환하는 DataServiceQuery 또는 LINQ 쿼리를 통해 클래스 생성자 메서드 중 하나를 호출하여 DataServiceCollection 클래스의 새 인스턴스를 만듭니다. 이 IEnumerable은 OData 피드에서 구체화되는 개체 소스를 바인딩 컬렉션에 제공합니다. 자세한 내용은 개체 구체화(WCF Data Services)를 참조하십시오. 기본적으로 컬렉션에 삽입된 항목 및 바인딩된 개체의 변경 내용은 DataServiceContext에 의해 자동으로 추적됩니다. 수동으로 이러한 변경 내용을 추적해야 하는 경우 trackingMode 매개 변수를 사용하는 생성자 메서드 중 하나를 호출하고 None 값을 지정합니다.

다음 예제에서는 제공된 DataServiceContext 및 관련 주문과 함께 모든 고객을 반환하는 DataServiceQuery를 기반으로 DataServiceCollection 인스턴스를 만드는 방법을 보여 줍니다.

' Create a new collection that contains all customers and related orders.
Dim trackedCustomers As DataServiceCollection(Of Customer) = _
        New DataServiceCollection(Of Customer)(context.Customers.Expand("Orders"))
// Create a new collection that contains all customers and related orders.
DataServiceCollection<Customer> trackedCustomers = 
    new DataServiceCollection<Customer>(context.Customers.Expand("Orders"));

Windows Presentation Foundation 요소에 데이터 바인딩

DataServiceCollection 클래스는 ObservableCollection 클래스에서 상속하기 때문에 바인딩에 ObservableCollection 클래스를 사용할 때처럼 WPF(Windows Presentation Foundation) 응용 프로그램의 요소 또는 컨트롤에 개체를 바인딩할 수 있습니다. 자세한 내용은 데이터 바인딩(Windows Presentation Foundation)을 참조하십시오. 데이터 서비스 데이터를 WPF 컨트롤에 바인딩하는 한 가지 방법은 요소의 DataContext 속성을 쿼리 결과가 포함된 DataServiceCollection 클래스 인스턴스로 설정하는 것입니다. 이 경우 ItemsSource 속성을 사용하여 컨트롤의 개체 소스를 설정합니다. DisplayMemberPath 속성을 사용하면 표시할 바인딩된 개체의 속성을 지정할 수 있습니다. 탐색 속성에서 반환된 관련 개체에 요소를 바인딩하는 경우 ItemsSource 속성의 정의된 바인딩에 경로를 포함합니다. 이 경로는 부모 컨트롤의 DataContext 속성에 설정된 루트 개체에 상대적입니다. 다음 예제에서는 StackPanel 요소의 DataContext 속성을 설정하여 부모 컨트롤을 고객 개체의 DataServiceCollection에 바인딩합니다.

' 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
// 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.
this.LayoutRoot.DataContext = trackedCustomers;

다음 예제에서는 자식 DataGridComboBox 컨트롤의 XAML 바인딩 정의를 보여 줍니다.

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

자세한 내용은 방법: Windows Presentation Foundation 요소에 데이터 바인딩(WCF Data Services)을 참조하십시오.

엔터티가 일대다 또는 다대다 관계에 참여하는 경우 관계의 탐색 속성에서 관련 개체의 컬렉션을 반환합니다. 서비스 참조 추가 대화 상자나 DataSvcUtil.exe 도구를 사용하여 클라이언트 데이터 서비스 클래스를 생성하는 경우 탐색 속성에서 DataServiceCollection 인스턴스를 반환합니다. 이렇게 하면 관련 개체를 컨트롤에 바인딩하고 관련 엔터티에 대한 마스터-세부 정보 바인딩 패턴과 같은 일반적인 WPF 바인딩 시나리오를 지원할 수 있습니다. 위의 XAML 예제에 포함된 XAML 코드에서는 마스터 DataServiceCollection을 루트 데이터 요소에 바인딩합니다. 주문 DataGrid는 선택한 고객 개체에서 반환된 주문 DataServiceCollection에 바인딩되고, 고객 개체는 Window의 루트 데이터 요소에 바인딩됩니다.

Windows Forms 컨트롤에 데이터 바인딩

개체를 Windows Form 컨트롤에 바인딩하려면 컨트롤의 DataSource 속성을 쿼리 결과가 포함된 DataServiceCollection 클래스 인스턴스로 설정합니다.

Ee373844.note(ko-kr,VS.100).gif참고:
데이터 바인딩은 INotifyCollectionChangedINotifyPropertyChanged 인터페이스를 구현하여 변경 이벤트를 수신 대기하는 컨트롤에만 지원됩니다.컨트롤이 이러한 종류의 변경 알림을 지원하지 않으면 기본 DataServiceCollection에 대한 변경 내용이 바인딩된 컨트롤에 반영되지 않습니다.

다음 예제에서는 DataServiceCollectionComboBox 컨트롤에 바인딩합니다.

' Create a new collection for binding based on the LINQ query.
trackedCustomers = New DataServiceCollection(Of Customer)(customerQuery)

'Bind the Customers combobox to the collection.
customersComboBox.DisplayMember = "CustomerID"
customersComboBox.DataSource = trackedCustomers
// Create a new collection for binding based on the LINQ query.
trackedCustomers = new DataServiceCollection<Customer>(customerQuery);

//Bind the Customers combobox to the collection.
customersComboBox.DisplayMember = "CustomerID";
customersComboBox.DataSource = trackedCustomers;

서비스 참조 추가 대화 상자를 사용하여 클라이언트 데이터 서비스 클래스를 생성하는 경우 생성된 DataServiceContext를 기반으로 하는 프로젝트 데이터 소스도 만들어집니다. 이 데이터 소스를 사용하면 데이터 소스 창에서 디자이너로 항목을 끌어다 놓는 간단한 방법으로 데이터 서비스의 데이터를 표시하는 UI 요소나 컨트롤을 만들 수 있습니다. 이러한 항목은 데이터 소스에 바인딩된 응용 프로그램 UI의 요소가 됩니다. 자세한 내용은 방법: 프로젝트 데이터 소스를 사용하여 데이터 바인딩(WCF Data Services)을 참조하십시오.

페이징 데이터 바인딩

단일 응답 메시지에 반환되는 쿼리된 데이터 양을 제한하도록 데이터 서비스를 구성할 수 있습니다. 자세한 내용은 데이터 서비스 구성(WCF Data Services)을 참조하십시오. 데이터 서비스에서 응답 데이터를 페이징하는 경우 각 응답에 다음 결과 페이지를 반환하는 데 사용되는 링크가 포함됩니다. 자세한 내용은 지연된 콘텐츠 로드(WCF Data Services)를 참조하십시오. 이 경우 다음 예제와 같이 NextLinkUri 속성에서 가져온 URI를 전달하여 DataServiceCollectionLoad 메서드를 호출함으로써 명시적으로 페이지를 로드해야 합니다.

    ' Create a new collection for binding based on the LINQ query.
trackedCustomers = New DataServiceCollection(Of Customer)(customerQuery)

    ' Load all pages of the response at once.
While trackedCustomers.Continuation IsNot Nothing
    trackedCustomers.Load( _
            context.Execute(Of Customer)(trackedCustomers.Continuation.NextLinkUri))
End While
// Create a new collection for binding based on the LINQ query.
trackedCustomers = new DataServiceCollection<Customer>(customerQuery);

// Load all pages of the response at once.
while (trackedCustomers.Continuation != null)
{
    trackedCustomers.Load(
        context.Execute<Customer>(trackedCustomers.Continuation.NextLinkUri));
}

관련 개체도 유사한 방식으로 로드됩니다. 자세한 내용은 방법: Windows Presentation Foundation 요소에 데이터 바인딩(WCF Data Services)을 참조하십시오.

데이터 바인딩 동작 사용자 지정

DataServiceCollection 클래스를 사용하면 개체 추가 또는 제거와 같이 컬렉션이 변경될 때 및 컬렉션의 개체 속성이 변경될 때 발생하는 이벤트를 가로챌 수 있습니다. 데이터 바인딩 이벤트를 수정하여 다음 제약 조건이 포함된 기본 동작을 재정의할 수 있습니다.

  • 대리자 내에서는 유효성 검사가 수행되지 않습니다.

  • 엔터티를 추가하면 자동으로 관련 엔터티가 추가됩니다.

  • 엔터티를 삭제해도 관련 엔터티는 삭제되지 않습니다.

DataServiceCollection 인스턴스를 만드는 경우 바인딩된 개체가 변경될 때 발생하는 이벤트를 처리하는 메서드에 대리자를 정의하는 다음 매개 변수를 지정할 수 있습니다.

  • entityChanged - 바인딩된 개체의 속성이 변경될 때 호출되는 메서드입니다. 이 Func 대리자는 EntityChangedParams 개체를 받아들이고 DataServiceContext에서 UpdateObject를 호출하는 기본 동작이 수행되어야 하는지 여부를 나타내는 부울 값을 반환합니다.

  • entityCollectionChanged - 개체가 바인딩 컬렉션에 추가 또는 제거될 때 호출되는 메서드입니다. 이 Func 대리자는 EntityCollectionChangedParams 개체를 받아들이고 Add 작업에 대해 AddObject를 호출하거나 DataServiceContext에서 Remove 작업에 대해 DeleteObject를 호출하는 기본 동작이 수행되어야 하는지 여부를 나타내는 부울 값을 반환합니다.

Ee373844.note(ko-kr,VS.100).gif참고:
WCF Data Services 는 이러한 대리자에 구현한 사용자 지정 동작의 유효성 검사를 수행하지 않습니다.

다음 예제에서 Remove 작업은 DeleteLinkDeleteObject 메서드를 호출하여 삭제된 Orders 엔터티에 속하는 Orders_Details 엔터티를 제거하도록 사용자 지정됩니다. 이 사용자 지정 작업은 부모 엔터티가 삭제될 때 종속 엔터티가 자동으로 삭제되지 않으므로 수행됩니다.

' 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 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;
    }
}

자세한 내용은 방법: 데이터 바인딩 동작 사용자 지정(WCF Data Services)을 참조하십시오.

Remove 메서드를 사용하여 DataServiceCollection에서 개체가 제거될 때의 기본 동작은 해당 개체가 DataServiceContext에서도 삭제된 것으로 표시되는 것입니다. 이 동작을 변경하려면 CollectionChanged 이벤트가 발생할 때 호출되는 entityCollectionChanged 매개 변수의 메서드로 대리자를 지정합니다.

사용자 지정 클라이언트 데이터 클래스를 사용하여 데이터 바인딩

개체를 DataServiceCollection으로 로드할 수 있으려면 개체 자체에서 INotifyPropertyChanged 인터페이스를 구현해야 합니다. 서비스 참조 추가 대화 상자나 DataSvcUtil.exe 도구를 사용할 때 생성되는 데이터 서비스 클라이언트 클래스는 이 인터페이스를 구현합니다. 고유한 클라이언트 데이터 클래스를 제공하는 경우 데이터 바인딩에 다른 컬렉션 형식을 사용해야 합니다. 개체가 변경되면 데이터 바인딩된 컨트롤에서 이벤트를 처리하여 DataServiceContext 클래스의 다음 메서드를 호출해야 합니다.

  • AddObject - 새 개체가 컬렉션에 추가된 경우

  • DeleteObject - 개체가 컬렉션에서 제거된 경우

  • UpdateObject - 컬렉션에 있는 개체의 속성이 변경된 경우

  • AddLink - 개체가 관련 개체의 컬렉션에 추가된 경우

  • SetLink - 개체가 관련 개체의 컬렉션에 추가된 경우

자세한 내용은 데이터 서비스 업데이트(WCF Data Services)를 참조하십시오.

참고 항목

작업

방법: 수동으로 클라이언트 데이터 서비스 클래스 생성(WCF Data Services)
방법: 데이터 서비스 참조 추가(WCF Data Services)