All Blog Posts

Silverlight Tip: Binding objects to a ComboBox

I was recently adding a ComboBox control to my Silverlight application and found myself wondering why I was stumped on something that seemed to be easy.  After some searching I came up with the following solution.


Populate a Silverlight ComboBox with items (from a database or not) where the "SelectedValue" of the ComboBox is different than the "DisplayValue".

My Solution

In summary, I did the following:
  1. Created a class NameValuePair which contains fields for Name and Value.
  2. Set the DisplayMemberPath property of my ComboBox to "Name".
  3. Create a object which is a List of NameValuePair objects.
  4. Loop through my objects in code, create an instance of the NameValuePair class and add that object to the list.
  5. Set the ItemsSource property to my new list  

Code for my solution

1. NameValuePair class:

public class NameValuePair { public NameValuePair(string name, string value) { this.Name = name; this.Value = value; } private string _name = string.Empty; public string Name { get { return _name; } set { _name = value; } } private string _value = string.Empty; public string Value { get { return _value; } set { _value = value; } } }

2. ComboBox XAML

<ComboBox Width="80" Height="25" SelectedIndex="0" x:Name="comboImageType" DisplayMemberPath="Name" ><ComboBox>

3. Create new List of NameValuePair objects

List<NameValuePair> lstImageType = new List<NameValuePair>();

4. Add objects to my new List

lstImageType.Add(new NameValuePair(BABEditBoard.Resources.StringResources.AnyType, "AnyType")); lstImageType.Add(new NameValuePair(BABEditBoard.Resources.StringResources.ClipArt, "ClipArt")); lstImageType.Add(new NameValuePair(BABEditBoard.Resources.StringResources.Faces, "Faces")); lstImageType.Add(new NameValuePair(BABEditBoard.Resources.StringResources.Photos, "Photos")); lstImageType.Add(new NameValuePair(BABEditBoard.Resources.StringResources.LineArt, "LineArt"));  

5. Bind list to the ComboBox

comboImageType.ItemsSource = lstImageType;
I can also set the DisplayMemberPath property in code like this: comboImageType.DisplayMemberPath = "Name";  

Retrieving Data from the ComboBox

Now that the ComboBox is filled with your list, here is some code to retrieve the Value or Name of the SelectedValue for your ComboBox.

NameValuePair imageTypeValue = (NameValuePair)comboImageType.SelectedItem; string imageValue = imageTypeValue.Value; string imageName = imageTypeValue.Name;
That's all there is to it.  Now you can use your own classes instead of the NameValuePair class.  This class has been a nice tool in my Silverlight toolbox. Thanks!