다음을 통해 공유


방법: Windows Presentation Foundation 컨트롤에 개체 바인딩(Entity Framework)

Entity Framework 를 사용하면 ListBox 또는 ComboBox와 같은 WPF(Windows Presentation Foundation) 요소를 EntityCollection 또는 ObjectQuery 결과에 바인딩할 수 있습니다. 컨트롤을 ObjectQuery에 직접 바인딩하지 않는 것이 좋습니다. 대신, 컨트롤을 Execute 메서드의 결과에 바인딩하십시오. LINQ 쿼리로 작업하려면 쿼리의 결과를 ObjectQuery로 캐스팅하고 Execute를 호출하는 것이 좋습니다.

자세한 내용은 컨트롤에 개체 바인딩(Entity Framework)을 참조하십시오.

이 항목의 예제는 AdventureWorks Sales 모델을 기반으로 합니다. 이 예제의 코드를 실행하려면 프로젝트에 AdventureWorks Sales 모델을 추가하고 Entity Framework 를 사용하도록 프로젝트를 구성해야 합니다. 이렇게 하려면 방법: Entity Framework 프로젝트 수동 구성방법: 수동으로 모델 및 매핑 파일 정의(Entity Framework)의 절차를 수행합니다.

예제

다음 예제는 WPF에서 SalesOrders 창을 정의하는 XAML(Extensible Application Markup Language) 페이지에 대한 코드 숨김 페이지에서 가져온 것입니다. 창이 로드되면 ObjectQueryExecute 메서드를 호출하는 방법으로 SalesOrderHeader 및 관련된 SalesOrderDetail 개체의 ObjectResult가 반환됩니다. 이 결과는 Grid 컨트롤의 DataContext 속성에 바인딩됩니다.

Imports System
Imports System.Data
Imports System.Data.Objects
Imports System.Windows
Imports System.Linq
Imports Microsoft.Samples.Edm

Namespace Microsoft.Samples.Edm
    Partial Public Class SalesOrders
        Inherits Window
        Private context As AdventureWorksEntities
        Private customerId As Integer = 277
        Private Sub SalesOrdersForm_Loaded( _
            ByVal sender As Object, ByVal e As RoutedEventArgs)

            ' Instantiate the ObjectContext.
            context = New AdventureWorksEntities()

            ' Define a query that returns orders for a customer.
            ' Because lazy loading is on by default, SalesOrderDetails
            ' related to a SalesOrderHeader will be loaded when the query
            ' is executed.
            Dim query = From o In context.SalesOrderHeaders Where o.CustomerID = customerId

            ' Execute the query and bind the result to the OrderItems control.
            Me.orderItemsGrid.DataContext = CType(query, ObjectQuery).Execute(MergeOption.AppendOnly)
        End Sub
        Private Sub buttonClose_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Me.Close()
        End Sub
        Public Sub New()
            InitializeComponent()
        End Sub
    End Class
End Namespace
using System;
using System.Data;
using System.Data.Objects;
using System.Windows;
using System.Linq;

namespace Microsoft.Samples.Edm
{
    /// <summary>
    /// Interaction logic for SalesOrders.xaml
    /// </summary>
    public partial class SalesOrders : Window
    {
        private AdventureWorksEntities context;
        private int customerId = 277;

        private void SalesOrdersForm_Loaded(object sender, RoutedEventArgs e)
        {
            // Instantiate the ObjectContext.
            context = new AdventureWorksEntities();

            // Define a query that returns orders for a customer.
            // Because lazy loading is on by default, SalesOrderDetails
            // related to a SalesOrderHeader will be loaded when the query
            // is executed.
            var query = from o in context.SalesOrderHeaders
                         where o.CustomerID == customerId
                         select o;

            // Execute the query and bind the result to the OrderItems control.
            this.orderItemsGrid.DataContext = ((ObjectQuery)query).Execute(MergeOption.AppendOnly);
        }

        private void buttonClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        public SalesOrders()
        {
            InitializeComponent();
        }
    }
}

다음은 WPF에서 SalesOrders 창을 정의하는 XAML입니다. ComboBoxItemsSource 속성은 코드 숨김 페이지에서 정의된 ObjectResult<SalesOrderHeader> 데이터 소스에 바인딩됩니다. 주문을 선택하면 SalesOrderDetail 개체의 관련 EntityCollectionItemsSource 속성으로 지정된 ListView에 바인딩됩니다. 바인딩에서 Path=SalesOrderDetail의 경로 값은 ListViewEntityCollection을 반환하는 SalesOrderDetail 속성에 바인딩되도록 합니다.

    <Window x:Class="Microsoft.Samples.Edm.SalesOrders"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    Title="Customer Sales Orders" Height="335" Width="425" 
        Name="SalesOrdersForm" Loaded="SalesOrdersForm_Loaded">
        <Grid Name="orderItemsGrid">
        <ComboBox DisplayMemberPath="SalesOrderID" ItemsSource="{Binding}"
                  IsSynchronizedWithCurrentItem="true" 
                  Height="23" Margin="122,12,198,0" Name="comboBoxOrder" VerticalAlignment="Top"/>
        <ListView ItemsSource="{Binding Path=SalesOrderDetails}" Name="listViewItems" Margin="34,46,34,50">
            <ListView.View>
                <GridView AllowsColumnReorder="False" ColumnHeaderToolTip="Line Items">
                    <GridViewColumn DisplayMemberBinding="{Binding Path=ProductID}" 
                        Header="Product" Width="50"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Path=OrderQty}" 
                        Header="Quantity" Width="50"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Path=UnitPrice}" 
                        Header="Cost" Width="50"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Path=LineTotal}" 
                        Header="Line Total" Width="80"/>
                </GridView>
            </ListView.View>
        </ListView>
        <Label Height="28" Margin="34,12,0,0" Name="orderLabel" VerticalAlignment="Top" 
               HorizontalAlignment="Left" Width="93">Order:</Label>
        <Button Height="23" HorizontalAlignment="Right" Margin="0,0,12,12" 
                Name="buttonClose" VerticalAlignment="Bottom" Width="75" Click="buttonClose_Click">Close</Button>
    </Grid>
</Window>

참고 항목

작업

방법: Windows Form 컨트롤에 개체 바인딩(Entity Framework)
방법: 프로젝트 데이터 소스로 개체 추가(Entity Framework)

개념

개체 사용(Entity Framework)
컨트롤에 개체 바인딩(Entity Framework)

기타 리소스

데이터 바인딩 개요(WPF)