Wednesday, February 10, 2010

Making the Silverlight ComboBox bind to multiple columns.

It is actually very simple to make the Silverlight ComboBox show multiple columns, but took me a while to figure out how. Below is what I learned.

The Setup

Let’s assume you have a ComboBox defined in XAML as follows

<ComboBox x:Name="cboTest" Width="100" Height="20" />

Now you want to populate it with some data that you get from the database (through WCF, Web Service, etc). All you have to do is set the ItemsSource property as shown below. In this case, GetMyData() returns a List<Person> type. You can do this in the code behind.

cboTest.ItemsSource = GetMyPersonData();

Now you want to select the appropriate item (the item with PeopleID equal to 123 in our sample) in the ComboBox.


Person foundItem = (cboTest.ItemsSource as ObservableCollection<Person>).FirstOrDefault(p => p.PeopleID == 123);
cboAccountManager.SelectedItem = foundItem;

Showing One Property for each Item in the ComboBox

This is easy, just set the DisplayMemberPath in your XAML or Code behind. In this case, we will display a ComboBox that shows a list of first names.

XAML

<ComboBox x:Name="cboTest" Width="100" Height="20" DisplayMemberPath="FirstName" />

Code-behind

cboTest.DisplayMemberPath="FirstName";

Showing Multiple Properties for each Item in the ComboBox

This is actually not bad at all either (once you see how to do it). You will want to remove any code or XAML that sets the DisplayMemberPath. Now all you have to do is change your XAML to look the way you want. Here is an example, that shows the FirstName and LastName properties of our Person object concatenated with a space.

<ComboBox x:Name="cboTest">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName, Mode=OneWay}" />
<TextBlock Text=" " />
<TextBlock Text="{Binding LastName, Mode=OneWay}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
You are free to use whatever combination of controls you need to make your multi column layout or maybe just custom format you want.