Tech Talk A software developer on all things tech, and then some

20Feb/103

WPF Filtering a Combobox

Setting Up the ComboBox

So in WPF, I wanted to filter a combobox to treat it as an autocompletebox.

Note : This tutorial expects you understand how to populate the combobox to have the data to filter.

I started off enabling two items on the properties tab of the combobox.

isEditable

Allows the user to be able to type in the combobox.

isTextSearchEnabled

Tells the combobox to suggest text and finishes your text with the closest word possible.
*Update (1/31/2013)- It looks like since posting this, you might be better off disabling this to filter the items properly.

Creating the Filter

That was the easy part. Now we have to create and code the filter. The first part is creating a predicate.

private bool FilterPredicate(object obj)
{
    string text = obj as string;
    if (text != null)
    {
         if (text.contains(combobox.Text))
        {
               return true;
        }
        return false
    }
    else
    {
          //if the string is null, return false
          return false;
    }

}

Next we assign the predicate to the combobox filter event. This will tell what filter to run on the combobox.

combobox.Items.Filter += this.FilterPredicate;

Finally we need to set up some of the functionality of the combobox. We can do this in an OnClick event.

private void combobox_KeyDown(object sender, KeyEventArgs e)
{
	if ((e.Key == Key.Enter) || (e.Key == Key.Tab) || (e.Key == Key.Return))
	{
		//Formatting options
		combobox.Items.Filter = null;
	}
	else if ((e.Key == Key.Down) || (e.Key == Key.Up))
	{
		combobox.IsDropDownOpen = true;
	}
	else
	{
		combobox.IsDropDownOpen = true;
		combobox.Items.Filter += this.FilterPredicate;
	}
}

There you have it, an autocompletebox. A few things to note. There may be better ways to do this (esp with the key down events, this was done as a uber quick example), but I wanted to give the beginning user an introduction on how to program this. If you have any questions please post a comment.

Comments (3) Trackbacks (0)
  1. Umm… the combobox doesn’t have a filter event. What combobox are you using?

  2. Thank you for the great tutorial!


Leave a Reply

No trackbacks yet.

%d bloggers like this: