共用方式為


HOW TO:將物件繫結到 Windows Presentation Foundation 控制項 (Entity Framework)

Entity Framework 可以讓您將 Windows Presentation Foundation (WPF) 項目 (例如 ListBoxComboBox) 繫結到 EntityCollectionObjectQuery 結果。 建議您不要將控制項直接繫結到 ObjectQuery, 最好是將它們繫結到 Execute 方法的結果。 如果您想要使用 LINQ 查詢,建議您將查詢的結果轉換成 ObjectQuery 並且呼叫 Execute

如需詳細資訊,請參閱將物件與控制項繫結 (Entity Framework)

本主題的範例是根據 Adventure Works Sales Model。 若要執行此範例中的程式碼,您必須已經將 AdventureWorks Sales Model 加入到專案中,並設定您的專案使用 Entity Framework 。 若要這樣做,請完成 HOW TO:手動設定 Entity Framework 專案HOW TO:手動定義模型和對應檔 (Entity Framework) 中的程序。

範例

下列範例取自用於定義 WPF 中 SalesOrders 視窗之可延伸應用程式標記語言 (XAML) 頁面的程式碼後置頁面。 載入視窗時,SalesOrderHeaderObjectResult 和相關的 SalesOrderDetail 物件,是藉由呼叫 ObjectQueryExecute 方法所傳回的。 這個結果會繫結到 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();
        }
    }
}

下列 XAML 用於定義 WPF 中的 SalesOrders 視窗。 ComboBoxItemsSource 屬性會繫結到程式碼後置頁面中定義的 ObjectResult<SalesOrderHeader> 資料來源。 選取某個訂單時,SalesOrderDetail 物件的相關 EntityCollection 會繫結到由 ItemsSource 屬性所指定的 ListView。 繫結中 Path=SalesOrderDetail 的路徑值,可以確保將 ListView 繫結到會傳回 EntityCollectionSalesOrderDetail 屬性。

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

另請參閱

工作

HOW TO:將物件繫結到 Windows Form 控制項 (Entity Framework)
HOW TO:將物件加入做為專案資料來源 (Entity Framework)

概念

使用物件
將物件與控制項繫結 (Entity Framework)

其他資源

資料繫結概觀 (WPF)