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:
<local:AutoCompleteTextBox Height="23" Width="240" x:Name="textBox1"
DelayTime="500" Threshold="2"/>
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.
textBox1.AddItem(new AutoCompleteEntry
("Toyota Camry", "Toyota Camry", "camry", "car", "sedan"));
textBox1.AddItem(new AutoCompleteEntry
("Toyota Corolla", "Toyota Corolla", "corolla", "car", "compact"));
textBox1.AddItem(new AutoCompleteEntry
("Toyota Tundra", "Toyota Tundra", "tundra", "truck"));
textBox1.AddItem(new AutoCompleteEntry("Chevy Impala", null));
textBox1.AddItem(new AutoCompleteEntry
("Chevy Tahoe", "Chevy Tahoe", "tahoe", "truck", "SUV"));
textBox1.AddItem(new AutoCompleteEntry
("Chevrolet Malibu", "Chevrolet Malibu", "malibu", "car", "sedan"));
If for example, the user types in "car", all the entries with the "car" keyword will be suggested.
I hope you find this solution helpful. If you find any errors or have questions, feel free to contact me.
History
- 30th May, 2008: First release
|
|
 |
 | Issue with WPF AutoComplete TextBox with Chinese and Japanese inputs sandyyyyyyyyyy | 0:35 19 Nov '09 |
|
 |
Well I am using our WPF autoComplete textbox and its working excellent in all the languages.
But when I use chinese or japanese language as input language it causes the application to crash.
this has been a serious issue I have been facing  
Please help me out in this
|
|
|
|
 |
 | My vote of 2 realvasche | 8:36 23 Oct '09 |
|
 |
Autocomplete with no keyboard nav? You have to be kidding.
|
|
|
|
 |
 | chinese IME issue nnnnimisha | 21:17 5 Aug '09 |
|
 |
Hello All,
The control doesnot seems to be working when input is being made through Chinese IME 3.0 and the entire applications crashes.
Can you suggest any solution to the issue.  
|
|
|
|
 |
 | How can I change the Background Color of the AutoComplete TextBox? microsoft_kc | 21:59 23 Jun '09 |
|
 |
Hi,
I checked a lot.... but unfortunately, I am unable to change the background color of the autocomplete textbox.
Please help me to find out the same. I need it ASAP.
Thank you in advance.
Regards, - Kunal Chowdhury ( My Blog)
|
|
|
|
 |
|
 |
Related to this is that this solution doesn't make it easy to create a transparent background on the textbox - which is requred by my application. Any suggestions?
|
|
|
|
 |
 | Nice One kapil bhavsar | 0:49 8 May '09 |
|
 |
How bout porting it to Silverlight ..
|
|
|
|
 |
 | My vote of 2 RandomEngy | 8:44 14 Apr '09 |
|
 |
Solution is hack-like, autocomplete is not responsive and does not use async.
|
|
|
|
 |
 | Wait hold on... is your ComboBox hiding behind the text field? Member 4030005 | 8:41 14 Apr '09 |
|
 |
It seems like you just have a ComboBox and are hiding the main portion of it with your TextBox, and are opening it programatically, letting the drop-down peek out. That seems a little bit hack-like to me.
|
|
|
|
 |
 | Thanks!! DZaK83 | 14:11 19 Mar '09 |
|
 |
Simple and work great! 
Bests, Jacek Ciereszko
Work smart not hard
|
|
|
|
 |
 | Another alternative toidy | 8:15 30 Sep '08 |
|
|
 |
 | keyboard oriented selection john c gibbons | 6:24 22 Sep '08 |
|
 |
kinda hacky but quick, adding this handler registration
textBox.PreviewKeyDown += new KeyEventHandler(textBox_PreviewKeyDown);
with a handler like this guy
void textBox_PreviewKeyDown(object sender, KeyEventArgs e) { if (comboBox.Items.Count > 0 && e.Key == Key.Down) { comboBox.Focus(); } }
allow for a simple move to the combobox for keyboard oriented selection like you might see after the matching results pop as in google suggested search, others.
good code!
|
|
|
|
 |
 | No keyboard navigation? armentage | 5:59 17 Jul '08 |
|
 |
You need to use your mouse to pick an item? Really??
|
|
|
|
 |
 | ComboBox Selection Andrewiski | 16:54 2 Jun '08 |
|
 |
I love the example it was perfect for what I am trying to accomplish. I have a question and wondering if you have ran into it and had a solution.
When you type and there is a match on one or more items the combobox appears but a down arrow will not highlight the first item. If you move the mouise over the first item it highlights and then the arrows will work and once you have highlighted the item you want enter makes the selection.
Any Idea on how to get the comboBox to highlight (not Select) the first item so arrow down will traverse the list. I have tried a bunch of differnt approches but can't seem to find a way to accomplish this with out selecting the first value.
Thanks for the help.
Andy
Andrew DeVries has been a .Net programmer since 2003. He currently works as a consultant designing custom software for windows as well as for the web. Currently he spends his days designing custom web controls and custom data sources.
|
|
|
|
 |
|
 |
Andy, you can trap the key press action on the textbox something like
textBox.KeyUp += new KeyEventHandler(textBox_Keyup);
then select the first item in the combobox and give it focus. You will need to turn off or not doing anything for SelectionChanged event on the combobox for this case.
private void textBox_Keyup(object sender, KeyEventArgs e) { if (e.Key == Key.Down) { if (comboBox.IsDropDownOpen) { comboBox.SelectionChanged -= new SelectionChangedEventHandler(comboBox_SelectionChanged); comboBox.SelectedIndex = 0; comboBox.Focus(); comboBox.SelectionChanged += new SelectionChangedEventHandler(comboBox_SelectionChanged); } } }
There should more elegant ways to trap the navigation/control keys. In my application I have code to throw an event when the user press the enter key, so this is what I would do.
|
|
|
|
 |
|
 |
I came to the same conclusion before I made it back here to read your post. The only annoying thing I ran into was that the ComboBoxItem gets a dashed black border because they are infocus. I tried to remove the dashed border but was not able. I could change the comboboxitem border to red etc but the dashed border was always on top. Maying a solid black border with a thickness of one gave me the look I wanted and hide the dashed border. I also added a comboBox.Clear(); and textBox.Focus() to the ComboBox.SelectionChangedHandler(); as it to was leaving a funny dashed border after the selection was changed and focus was not returning to the textbox.
Also all you need on the downarrow is comboBox.Focus() as this will leave the user typed text in the textbox with out having to set the SelectedIndex.
Thanks for the help.
Andy
Andrew DeVries has been a .Net programmer since 2003. He currently works as a consultant designing custom software for windows as well as for the web. Currently he spends his days designing custom web controls and custom data sources.
|
|
|
|
 |
 | Changing data set? Jim Weiler | 11:32 31 May '08 |
|
 |
Hello,
I have been working on an autocomplete textbox similar to your except not using WPF for some time now. My purpose is to simulate the google toolbar's autocomplete. My problem has always been that if the source of the autocomplete values is changed, the autocomplete area is not able to change the values fluidly and the redrawing is less than desirable, among other shortcomings. I am wondering if you have tested this scenario with your control and what kind of behavior it exhibits if the values are changed while being displayed.
-Jim
|
|
|
|
 |
|
 |
Jim, I have not tried the scenario where the data is changing while being displayed. My data source is pretty much static from the start. Implement some kind of data binding between my list and the sql db is on my todo list.
modified on Tuesday, June 3, 2008 12:40 AM
|
|
|
|
 |
|
 |
Hi,
I'm wondering if you'll get round to implement logic to bind your control to a database source. I'm a newbie in WPF and just started with PRISM so it's not clear to me how to bind a user control to a service.
|
|
|
|
 |
|
|