|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThis 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. BackgroundI 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 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 Using the CodeTo use this custom control in your application, you simply add the following files...
... 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 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"));
// null matching string will default with just the name
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
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||