Ioan Lazarciuc's Weblog I program, therefore I exist.

1Jun/0823

Auto Complete for Textboxes in WPF

Introduction

It is very common when entering a search string in a textbox to get a small list of valid search results that match the search string entered so far. This feature is called auto complete and it has been widely used in web pages and desktop applications alike.

From the developer's point of view, the auto complete feature has been implemented as part of the TextBox control in Windows Forms. That being said, I had a bit of a surprise when I could not find the functionality in the Windows Presentation Foundation TextBox control. Upon further online searches on the matter, I discovered that, in fact, auto complete has not been implemented for textboxes in WPF. The purpose of this post is to suggest (no pun intended) an implementation for the missing feature.

Functional Description

The entity we wish to create is a WPF user control that can be instantiated both through Xaml and code (C# or VB). We can either inherit from TextBox and add properties and methods required for auto complete, or we can create a control that can "wire up" the auto complete feature for any targeted TextBox control. The first approach not recommended due to the fact that a ListBox must be added to a TextBox. I chose to follow the second approach, perhaps being inspired by the AutoCompleteExtender in the ASP.NET AJAX Control Toolkit and also because it requires minimum intervention on existing WPF code (no need to change the type of many TextBox controls). Also, I did not include the targeted TextBox inside the custom control, in order to be able to apply this functionality on already existing code. The variant with the TextBox included can be found here.

A finite number of suggestions should be displayed as soon as a minimum number of  characters are typed, and then the suggestion list should be updated with each new modification to the search string. The maximum number of suggestions displayed should be configurable by means of a property. The user should be able to highlight a suggestion using the up/down keys, and be able to select a suggestion by pressing Tab or Enter in order to set the text of the target TextBox to that value. The means by which the suggestions are returned (from a web service, or simple method, etc.) should be as configurable as possible.