如何:将对象绑定到 Windows Presentation Foundation 控件(实体框架)

使用实体框架 可以将 Windows Presentation Foundation (WPF) 元素(如 ListBoxComboBox)绑定到 EntityCollectionObjectQuery 结果。 我们建议您不要将控件直接绑定到 ObjectQuery, 而应将控件绑定到 Execute 方法的结果。 若您更愿意使用 LINQ 查询,建议您将查询结果强制转换为 ObjectQuery 并调用 Execute

有关更多信息,请参见将对象绑定到控件(实体框架)

本主题中的示例基于 Adventure Works 销售模型。 若要运行本示例中的代码,必须已将 AdventureWorks 销售模型添加到您的项目中,并将项目配置为使用 实体框架 。 为此,请完成如何:手动配置实体框架项目如何:手动定义模型和映射文件(实体框架)中的过程。

示例

下面的示例摘自在 WPF 中定义 SalesOrders 窗口的可扩展应用程序标记语言 (XAML) 页的代码隐藏页。 在加载该窗口时,会通过调用 ObjectQueryExecute 方法来返回 SalesOrderHeader 和相关对象 SalesOrderDetailObjectResult。 此结果将绑定到 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 对象的相关 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>

另请参见

任务

如何:将对象绑定到 Windows 窗体控件(实体框架)
如何:将对象作为项目数据源添加(实体框架)

概念

使用对象(实体框架)
将对象绑定到控件(实体框架)

其他资源

数据绑定概述 (WPF)