How to Create a HTML-style ComboBox in WPF and C#

Before I started doing software development in C# and WPF, I spent quite a bit of time with HTML. Because of this, I was used to having the ability to create drop-down boxes (known as select in HTML) to display lists of information with a “front-end” value the user could see and a “back-end” value that held data.

For example, I could create a list of colors that would display the color’s name in the select box, but would then correspond to a hexadecimal value in the background:

[code lang=”xml” title=”HTML Select Example”]

<select>

<option value="#FF0000">Red</option>
<option value="#008000">Green</option>
<option value="#0000FF">Blue</option>

</select>

[/code]

Which looks like:

If the user selected “Green”, it would show up as “#008000” behind the scenes.

This type of control is known as a ComboBox in WPF and C# and has similar functionality, but by default you can’t store Name –> Value pairs in them like you can in HTML. In this guide, I’ll show you some simple code you can use to recreate this functionality.

Creating HTML-style ComboBox in WPF and C#

For this example, I wanted to create a drop-down menu for selecting the Parity value of a serial port connection. Parity is an enumeration in C# and has values like Parity.None, Parity.Even, and Parity.Odd, but I wanted to display just “None”, “Even”, and “Odd” to the user.

The first thing I did was to create a custom class that expands the functionality of the standard ComboBoxItem. This class will store the pretty front-facing name in a string called “contents” and store the data value in an object called “tag”.

If you’re familiar with ComboBoxItems, you’ll know that they already offer Content and Tag properties. These properties don’t function the same way they do in HTML, so I found it best to create my own custom class.

[code lang=”csharp” title=”CustomComboBoxItem.cs”]

// Contains the visible "Name" of the item.
private string _contents;
public string contents { get { return _contents; } set { _contents = value; } }

// Contains the hidden "Value" of the item.
private object _tag;
public object tag { get { return _tag; } set { _tag = value; } }

public CustomComboBoxItem(string contents, object tag)
{
this._contents = contents;
this._tag = tag;
}

// Only the Name will be displayed when the string value is used
public override string ToString() { return _contents; }

[/code]

I created my ComboBox in WPF and created a Loaded event to programmatically populate the values.

[code lang=”csharp” title=”comboBox_Parity WPF”]

<ComboBox Name="comboBox_Parity" Loaded="comboBox_Parity_Loaded" />

[/code]

And then created the corresponding comboBox_Parity_Loaded function in my C#  file where I added the CustomComboBoxItem items to the ComboBox. You can see that the first value I give it is its front-facing name, and the second is the value of the Parity enumeration.

[code lang=”csharp” title=”comboBox_Parity_Loaded”]

private void comboBox_Parity_Loaded(object sender, RoutedEventArgs e)
{
// Add the options with my custom class CustomComboBoxItem. This allows me to store a unique "Name"=content and "Value"=tag for each item
comboBox_Parity.Items.Add(new CustomComboBoxItem("None", "Parity.None"));
comboBox_Parity.Items.Add(new CustomComboBoxItem("Even", "Parity.Even"));
comboBox_Parity.Items.Add(new CustomComboBoxItem("Odd", "Parity.Odd"));
comboBox_Parity.Items.Add(new CustomComboBoxItem("Mark", "Parity.Mark"));
comboBox_Parity.Items.Add(new CustomComboBoxItem("Space", "Parity.Space"));
}

[/code]

Compiling and executing this program shows my ComboBox filled with items called “None”, “Even”, and “Odd”, but its selected value now corresponds with “Parity.None”, “Parity.Even”, and “Parity.Odd”.

To access the back-end value of the user’s selection in your code (I was using it to change a hardware setting), you need to cast the SelectedItem property of the ComboBox as a CustomComboBoxItem.

[code lang=”csharp”]
// This takes whatever item is selected in the comboBox and stores it in a new item called item_Parity. This gives you access
// to the properties of the CustomComboBoxItem like .tag and .content.

CustomComboBoxItem item_Parity = (CustomComboBoxItem)this.comboBox_Parity.SelectedItem;

[/code]

To test it out, you can use the following code to write the item’s name and corresponding value to the console.

[code lang=”csharp” title=”Accessing internal values of CustomComboBoxItem”]

Console.WriteLine("Item’s name is: " + item_Parity.contents + " and Item’s value is: " + item_Parity.tag.ToString());

[/code]

That’s it! You should now have HTML-style ComboBoxes in WPF and C#.


Posted

in

,

by

Comments

5 responses to “How to Create a HTML-style ComboBox in WPF and C#”

  1. Bryant Sombke Avatar

    Great code sample, this is a good approach to accomplishing this.

    But now for my beef with Microsoft: An HTML select actually creates a drop down list. The WPF combobox is actually a drop down list as well. A combo box works like the combination of a textbox and a drop down list, like the one provided in the ASP.NET AJAX Control Toolkit. Why does Microsoft not follow established naming standards, as well as not follow their own standards between their own technologies?

    It makes me confused, almost as confused as the time I had a business requirement to make checkboxes that look like radio buttons, because the stakeholder thought the roundness of the radio buttons looks better than the square-ness of the checkboxes.

    1. Evan Wondrasek Avatar

      Regarding the radio box/check box requirement… :-O

      If you were doing it in WPF, you could probably override the control’s visual style to make it square (I’ve overridden visual styles for other controls like textboxes and buttons to make them pretty, which is what I did for BreakTaker. But that might be just as much work as writing code to switch their actual functionality 🙂

      I agree with you about the inconsistencies in standards, I’ve noticed a few as well and it’s hard to remember the different conventions. Little things like margins in WPF: they follow the format “margin-left, margin-top, margin-right, margin-bottom” where CSS and HTML have always followed the standard “margin-top, margin-right, margin-bottom, margin-left”. Just strikes me as odd that they would deviate from a nearly ubiquitous standard on the web.

      1. Bryant Sombke Avatar

        When writing a Silverlight app, I remember looking for a DropDownList control, and couldn’t find one. I settled for the ComboBox control, only to find it was what I was looking for in the first place. As a lazy programmer, I usually don’t want to read the documentation in order find a basic UI element suitable for the task at hand.

        1. Evan Wondrasek Avatar

          Bryant, I’m just going to throw this out there: I think we should do some coding together.

  2. Somesh Avatar

    Hi,
    Your article are really awesome.actually i was in search for some good articles on WPF ComboBox and finally i got one.
    The most important is the simplicity which will be very helpful for the beginners.
    I have found another post over internet related to this post. It is also explain nicely about WPF ComboBox , you may check it by visiting following link…

    http://mindstick.com/Blog/156/WPF%20ComboBox

    Thanks Everyone!!
     

Leave a Reply to Bryant Sombke Cancel reply