Autocomplete TextBox in WPF (Using Only .NET and WPF Libraries)

Introduction

In this source sample I show how to add the autocomplete functionality in your WPF application's TextBox control using your own model data, .NET assemblies and WPF assemblies. There is no need to add any third-party NuGet package or any other DLL file. You can create your own after reading this article and by using the sample attached.

Description

This sample gives an overview of how to do autocomplete in WPF. The Autocomplete function is based on the following:

  1. A query provided by the user. It is the input that the user has typed into the control.

  2. List or collection of data that we have at the moment.

  3. A conditional statement to check whether the object or item in our list has the content or not.

Using this, we can create our own autocomplete feature for any TextBox. First define the model that we will use, you can extract the model from an SQL Server database, from Microsoft Azure data sources or from any other custom file also. I used the following:

C#

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Text;   
  5. using System.Threading.Tasks;   
  6.    
  7. namespace AutocompleteWpfSample   
  8. {   
  9.     class Model   
  10.     {   
  11.         static public List<string> GetData()   
  12.         {   
  13.             List<string> data = new List<string>();   
  14.    
  15.             data.Add("Afzaal");   
  16.             data.Add("Ahmad");   
  17.             data.Add("Zeeshan");   
  18.             data.Add("Daniyal");   
  19.             data.Add("Rizwan");   
  20.             data.Add("John");   
  21.             data.Add("Doe");   
  22.             data.Add("Johanna Doe");   
  23.             data.Add("Pakistan");   
  24.             data.Add("Microsoft");   
  25.             data.Add("Programming");   
  26.             data.Add("Visual Studio");   
  27.             data.Add("Sofiya");   
  28.             data.Add("Rihanna");   
  29.             data.Add("Eminem");   
  30.    
  31.             return data;   
  32.         }   
  33.     }   
  34. }   
The preceding code would provide us the data required to complete the functionality. Now, add the XAML controls that would be like this. All we need is:
  1. A TextBox: for user input.
  2. A StackPanel: for managing the TextBlocks being added.
  3. A Border: to separate the stuff from underground controls. Fancy stuff only.

XAML

  1. <TextBox Width="300" Padding="5, 3, 5, 3"    
  2.          KeyUp="TextBox_KeyUp" Name="textBox" />   
  3. <Border Width="298" Height="150" BorderBrush="Black"   
  4.         BorderThickness="1">   
  5.     <ScrollViewer VerticalScrollBarVisibility="Auto">   
  6.         <StackPanel Name="resultStack"></StackPanel>   
  7.     </ScrollViewer>   
  8. </Border>  
Great, that completes the UI. You would see that I have also attached an event handler to handle the user input. That is to run when the user inputs a character, I would search for the match in my Model. Have a look at the following C# code for the WPF application's Autocomplete feature.

C#
  1. private void TextBox_KeyUp(object sender, KeyEventArgs e)   
  2. {   
  3.      bool found = false;   
  4.      var border = (resultStack.Parent as ScrollViewer).Parent as Border;   
  5.      var data = Model.GetData();   
  6.    
  7.      string query = (sender as TextBox).Text;   
  8.    
  9.      if (query.Length == 0)   
  10.      {   
  11.           // Clear   
  12.           resultStack.Children.Clear();   
  13.           border.Visibility = System.Windows.Visibility.Collapsed;   
  14.       }   
  15.       else   
  16.       {   
  17.           border.Visibility = System.Windows.Visibility.Visible;   
  18.       }   
  19.    
  20.       // Clear the list   
  21.       resultStack.Children.Clear();   
  22.    
  23.       // Add the result   
  24.       foreach (var obj in data)   
  25.       {   
  26.           if (obj.ToLower().StartsWith(query.ToLower()))   
  27.           {   
  28.                // The word starts with this... Autocomplete must work   
  29.                addItem(obj);   
  30.                found = true;   
  31.           }   
  32.      }   
  33.    
  34.      if (!found)   
  35.      {   
  36.           resultStack.Children.Add(new TextBlock() { Text = "No results found." });   
  37.      }   
  38. }  
I also had the function to add the item to the StackPanel, showing that would be injustice. So here it is.

C#
  1. private void addItem(string text)   
  2. {   
  3.      TextBlock block = new TextBlock();   
  4.    
  5.      // Add the text   
  6.      block.Text = text;   
  7.    
  8.      // A little style...   
  9.      block.Margin = new Thickness(2, 3, 2, 3);   
  10.      block.Cursor = Cursors.Hand;   
  11.    
  12.      // Mouse events   
  13.      block.MouseLeftButtonUp += (sender, e) =>   
  14.      {   
  15.           textBox.Text = (sender as TextBlock).Text;   
  16.      };   
  17.    
  18.      block.MouseEnter += (sender, e) =>   
  19.      {   
  20.           TextBlock b = sender as TextBlock;   
  21.           b.Background = Brushes.PeachPuff;   
  22.      };   
  23.    
  24.      block.MouseLeave += (sender, e) =>   
  25.      {   
  26.           TextBlock b = sender as TextBlock;   
  27.           b.Background = Brushes.Transparent;   
  28.      };   
  29.    
  30.      // Add to the panel   
  31.      resultStack.Children.Add(block);   
  32. }  
The preceding code would now be able to add the new items to the list and would let the user choose which item to add to the TextBox.

Note

There are many other UI changes that I have made. So, you can surely ignore them. Such as mouse enter and mouse leave event handling to change the background color. 
 
Example of the project 
 
The following is the live example of this sample.
 
 
 
If we start typing something into it (that doesn't have a match) it would show the following UI:
 
 
 
Great, isn't it? Now if there is a query that has a match in the model of ours, then it would generate a new list and would show it to us. Have a look below.
 
 
 
Um, if you hover over the list item then you will see that it also reflects events, as already said in the Note section above.
 
 
 
Great. So, I hope you might have learned how to create autocomplete functionality in your TextBoxes using only WPF and .NET Framework's libraries without having to use other third-party applications and NuGet packages. That's all for now. :-) I hope I helped you. 

Next Recommended Readings