Introduction

This article demonstrates some basic steps on how to build an auto complete textbox custom control with WPF. I have looked at many auto completion textbox solutions, most of them suffered performance issues when filled with large amount of entries. This implementation attempts to mask that problem by not building the suggested list until the user is done typing.

Background

I needed an autocompletion textbox for my application that can search based not just on name but also on keywords. I found the solution posted by pfemiani. I like his idea of searching by keywords but the solution does not work for my WPF application without extensive modification. Then I came across a WPF solution from AskErnest.com using a textbox and combobox controls, so I decided to build my code upon that.

Ernest's suggestion is pretty simple, there are two children in the control, Textbox and Combobox. On the TextBox's TextChanged event, we would populate the list for the combobox using words matching the text in the textbox. On the ComboBox's SelectionChanged event, we set the text in the textbox using the content of the selected item of the Combobox. This works very well except that Ernest is only doing name matching and his blog doesn't provide the complete source code.

Another challenge that I'm facing is performance issue. My autocompletion textbox is backed by several thousand entries from a database, on some keyword I could have over 300 hits. Populating the combobox on every user keystroke feels sluggish. My solution is to start a timer on TextChanged event and populate the combobox list only when the timer expires. I tried this on my large database and it works beautifully. I can type a long name and not feel like I'm on a 286.

Using the Code

To use this custom control in your application, you simply add the following files...

AutoCompleteEntry.cs

AutoCompleteTextBox.xaml

AutoCompleteTextBox.xaml.cs

... to your project. Next, in the XAML file that you would like to use the auto complete textbox custom control, add this line to the header block.

xmlns:local="clr-namespace:WPFAutoCompleteTextbox"

Then in the XAML code, where you want to place the auto complete textbox, add:

In my example code, the name of the textbox is textBox1. You can get or set the text in the textbox by referring to textBox1.Text. The DelayTime property is the amount of time (in ms) that you want to delay after the user starts typing before populating the list. Leaving the DelayTime unset will default to 0, which is populating immediately after each user keystroke. The Threshold property controls the number of characters threshold, at or over that at we will start suggesting.

In the code behind of my example, I manually populate the search entries with a variety of cars and models.