242Microsoft Visual Studio 2010: A Beginner’s Guide

The previous example assigns the results of a LINQ query for Customer objects to the customerIDComboBox, but this is only the first step to getting the combo box to work properly; you must specify which property of Customer must display, which property of Customer maps to Order, and which property of Order to bind the selected item to. To do this binding, open the NewOrder.xaml file in the Designer, select the combo box, and set the properties as specified in Table 8-2.

The following XAML shows the results of the settings you should make in the Properties window, based on Table 8-2:

<ComboBox DisplayMemberPath="Name"

SelectedValue="{Binding Path=CustomerID}"

SelectedValuePath="CustomerID"

Grid.Column="1" Grid.Row="1"

Height="23" HorizontalAlignment="Left" Margin="3" Name="customerIDComboBox" VerticalAlignment="Center" Width="120">

</ComboBox>

DisplayMemberPath and SelectedValuePath are names of the properties from the Customer objects bound to the ComboBox. However, the SelectedValue syntax uses a binding expression, where Path identifies the property of the Order that will be assigned to with SelectedValuePath. The binding for SelectedValue is based on the Order object

Property

Explanation

ItemsSource

We set this through code in the Window_Loaded event. It holds the collection

 

of objects that will appear in the combo box. You need two properties, one to

 

display and one for the key of the object being displayed. The key will be used

 

to map the object back to the database or associate the object in a relationship

 

with another object. In the case of the Customer list, the properties of interest are

 

Name for display and CustomerID for key. Since we are creating a new Order,

 

the CustomerID for the Name selected in the combo box will be assigned to the

 

CustomerID field of the Order. That way, when the Order is saved, its database

 

record will have the CustomerID for the customer the user selected.

DisplayMemberPath

This is the Name property from each Customer object bound to the combo box.

 

 

SelectedValuePath

As explained for ItemsSource, you need to associate the selected Customer with

 

the Order being created. SelectedValuePath is the name of the Customer object’s

 

key, which is CustomerID in our example.

SelectedValue

When saving the Order, you must have the key associated with the selected

 

customer. The SelectedValue is a binding to the property of the Order that will

 

be set with the key from the selected Customer.

 

 

Table 8-2 ComboBox Properties for Data Binding

Page 265
Image 265
Microsoft 9GD00001 manual Property Explanation, ComboBox Properties for Data Binding