WPF Databinding with Entity Framework

Tuesday, August 12 2008

(Note Originally posted on DataDeveloper.NET in January 2008)

In this tutorial, you will create a simple Windows Presentation Form which uses LINQ to Entities queries against an Entity Framework Entity Data Model as the source for controls.

The page will have a drop down list of Customers. When a customer is selected, the customer's primary address information will be displayed.

Create a new WPF application and add an Entity Data Model

  1. Create a new WPF application. [For more help with WPF, see the MSDN Document Getting Started with Windows Presentation Foundation]
  2. Add an Entity Data Model for the AdventureWorksLT database to the project.

Add controls to the default Window

  1. Click the tab for Window1.XAML in the Document windows to view the empty default window.

    image
  2. From the toolbox, select a Label control.
    image
  3. Click in the design window to place the label control on the design surface. Drag the control to the desired position.
    image
  4. In the Properties window for the Label control, change the Content property from "Label" to "Adventure Works Customers"
  5. If necessary, click the label control on the design surface, then hover the mouse over the right border of the label. Click and drag the right border to the desired width.
    image
  6. In the toolbox, click the  ListBox control, then click in the Window design area to add a ListBox to the design surface.

    image
  7. Using the same method as you did with the label, resize the ListBox to reposition and make it wider.
    image
  8. Add three more labels to the window and in the Properties window, change their Content property to "Primary Address", "City" and "Country"

    image
  9. Add three more labels and in the Properties window, change their Border Thickness property to 1 and BorderBrush to Black. The BorderBrush property is changed using a drop-down list.
    Note: If you select all three labels in the designer using Ctrl+Click, it is possible to change the properties for all three at the same time.

    image

Query the awModel to provide data for binding

  1. Point to the outer border of the Window and double click to have Visual Studio automatically create the Window_Loaded event for the window.
    image
    VB Result:
    image
    C# Result
    image

  2. In the Window_Loaded event, copy the following code which will perform a LINQ to Entities query which drills through the Customer entity to find the Address entity belonging to the first CustomerAddress in the Customer's CustomerAddresses collection. The results will be used as the source for the ListBox Items.

    image

    VB
    Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) _
    Handles Me.Loaded 
    
      Dim aw = New awEntities
      Dim fullGraph = From cust In aw.Customers.Include("CustomerAddresses.Address") _
    From CustomerAddress In cust.CustomerAddresses.Take(1) _ Select cust, CustomerAddress Dim query = From cGraph In fullGraph _
    Select cGraph.cust.CustomerID, _ cGraph.cust.CompanyName, cGraph.CustomerAddress.AddressType, _ cGraph.CustomerAddress.Address.City, cGraph.CustomerAddress.Address.CountryRegion Me.ListBox1.ItemsSource = query End Sub
 C#
private void Window_Loaded(object sender, RoutedEventArgs e) { awEntities aw=new awEntities(); var fullGraph = from cust in aw.Customers.Include("CustomerAddresses.Address") from CustomerAddress in cust.CustomerAddresses.Take(1) select new { cust, CustomerAddress }; var query = from cGraph in fullGraph select new { cGraph.cust.CustomerID, cGraph.cust.CompanyName, cGraph.CustomerAddress.AddressType, cGraph.CustomerAddress.Address.City, cGraph.CustomerAddress.Address.CountryRegion }; listBox1.ItemsSource = query; }

Add DataTemplates and bindings to the XAML to display the bound data

  1. Open Window1 designer in the Document windows.
  2. If necessary, change the view to Split pane to view the Designer and the XAML simultaneously. You can do this with the pane icons at the bottom of the design window.

    image

    image
    Split View
  3. Click the ListView in the designer. The XAML code for the control will be highlighted.
  4. Add the following parameter to the ListBox

    ItemsSource="{Binding}"

    Result:

    <ListBox ItemsSource="{Binding}" Margin="15,36,17,0" Name="ListBox1" Height="100" VerticalAlignment="Top" />

  5. Delete the closing slash  ("/") at the end of the ListBox.
  6. Add the following code below the ListBox element.

      <ListBox.ItemTemplate>
        <DataTemplate>
          <TextBlock Text="{Binding Path=CompanyName}"/>
         </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>

    Result:

    <ListBox ItemsSource="{Binding}" Margin="15,36,17,0" Name="ListBox1" Height="100" VerticalAlignment="Top" >
        <ListBox.ItemTemplate>
          <DataTemplate>
            <TextBlock Text="{Binding Path=CompanyName}"/>
           </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

  7. In the designer, click the first of the three bordered labels. The XAML code for the label will be highlighted.

    image 
  8. Locate the default content string "Label" in the XAML code.
    image
    If the Label's XAML is not wrapped, you will need to scroll to the right to locate it.image
  9. Replace the content with the following code

    <Binding ElementName="ListBox1" Path="SelectedItem.AddressType"/>

    Result:

    <Label Height="28" Margin="121,0,37,78" Name="Label5" VerticalAlignment="Bottom"
           BorderThickness="1" BorderBrush="Black">
      <Binding ElementName="ListBox1" Path="SelectedItem.AddressType"/>
    </Label>

  10. Using the same technique, replace the "Label" content of the second bordered label with the following
     
    <Binding ElementName="ListBox1" Path="SelectedItem.City"/>
  11. Using the same technique, replace the "Label" content of the third bordered label with the following

    <Binding ElementName="ListBox1" Path="SelectedItem.CountryRegion"/>

 

Test out the app

That's it! Now it's time to run the app which you can do by pressing F5.

As you select different companies in the list box, you will see the address information change.