Share via


How to: Bind Objects to Windows Presentation Foundation Controls (Entity Framework)

Object Services enables you to bind Windows Presentation Foundation (WPF) elements such as a ListBox or ComboBox to an EntityCollection or to an ObjectQuery result. We recommend that you not bind controls directly to an ObjectQuery. Instead, bind controls to the result of the Execute method. For more information, see Binding Objects to Controls (Entity Framework).

The example in this topic is based on the Adventure Works Sales Model. To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework).

Example

The following example is from the code-behind page for an Extensible Application Markup Language (XAML) page that defines the SalesOrders window in WPF. When the window is loaded, an ObjectResult of SalesOrderHeader and related SalesOrderDetail objects are returned by calling the Execute method of the ObjectQuery. This result is bound to the DataContext property of a Grid control.

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

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)
            Try
                ' Instantiate the ObjectContext.
                context = New AdventureWorksEntities()

                ' Define a query that returns orders for a customer.
                Dim query As ObjectQuery(Of SalesOrderHeader) = context.SalesOrderHeader _
                    .Where("it.customerID = @customerid", _
                    New ObjectParameter("customerid", customerId)) '_
                '.Include("SalesOrderDetail")

                ' Execute the query and bind the result to the OrderItems control.
                Me.orderItemsGrid.DataContext = query.Execute(MergeOption.AppendOnly)
            Catch ex As EntitySqlException
                MessageBox.Show(ex.Message)
            End Try
        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 AdventureWorksModel;

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)
        {
            try
            {
                // Instantiate the ObjectContext.
                context = new AdventureWorksEntities();

                // Define a query that returns orders for a customer.
                ObjectQuery<SalesOrderHeader> query = context.SalesOrderHeader
                    .Where("it.customerID = @customerid",
                    new ObjectParameter("customerid", customerId))
                    .Include("SalesOrderDetail");
                
                // Execute the query and bind the result to the OrderItems control.
                this.orderItemsGrid.DataContext = query.Execute(MergeOption.AppendOnly);
            }
            catch (EntitySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

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

The following is the XAML that defines the SalesOrders window in WPF. The ItemsSource property of a ComboBox is bound to the ObjectResult<SalesOrderHeader> data source that is defined in the code-behind page. When an order is selected, the related EntityCollection of SalesOrderDetail objects is bound to the ListView that is specified by the ItemsSource property. A path value of Path=SalesOrderDetail in the binding ensures that the ListView is bound to the SalesOrderDetail property that returns an EntityCollection.

    <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=SalesOrderDetail}" 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>

See Also

Tasks

How to: Bind Objects to Windows Form Controls (Entity Framework)
How to: Add an Object as a Project Data Source (Entity Framework)

Concepts

Bind Entity Data to Controls (Application Scenarios)
Binding Objects to Controls (Entity Framework)

Other Resources

Working with Objects (Entity Framework Tasks)
Data Binding Overview (WPF)