In Focus

WPF Auto Complete/Suggestion Text Box Control

This article is about the creation of text box with auto complete/suggestion feature along with its integration within your code in WPF platform.

A good product requires good user interaction. Products that are using search boxes will be expected to have auto-completion/suggestion feature. In WPF platform, the default text box control does not have any built-in auto-completion/suggestion feature. There are many 3rd party libraries out there which provide auto-complete/suggestion text box control as a replacement to the default WPF text box control. Most of these libraries are available in the paid version and those which are available for free, are difficult to get integrated with your existing code. So, I have created a very simple AutoComplete/Suggestion control for WPF platform without using any external library.
 
You can easily integrate my control in your project.
 
Today, I shall be demonstrating the creation of a text box with auto-complete/suggestion feature along with its integration within your code in WPF platform.
 
 
Prerequisites
 
Following are the prerequisites before you proceed any further in this tutorial.
  1. Download Bootstrap Time Picker JQuery Plugin.
  2. Knowledge of Windows Presentation Form (WPF).
  3. Knowledge of C# Programming.
  4. Knowledge of C# LINQ.
You can download the complete source code of this tutorial from the below link. The sample code is being developed in Microsoft Visual Studio 2017 Professional.
Let's begin now.
 
Step 1
 
Create a new WPF application project and name it "WPFAutoCompleteTextBox".
 
Step 2
 
Create the "Views\UserControls\AutoCompleteTextBoxUserControl.xaml" file and replace the following code in it. 
  1. <UserControl x:Class="WPFAutoCompleteTextBox.Views.UserControls.AutoCompleteTextBoxUserControl"    
  2.              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
  4.              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     
  5.              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     
  6.              xmlns:local="clr-namespace:WPFAutoCompleteTextBox.Views.UserControls"    
  7.              mc:Ignorable="d"     
  8.              d:DesignHeight="480" d:DesignWidth="640">    
  9.     
  10.     <Grid>    
  11.         <StackPanel Orientation="Vertical"    
  12.                     VerticalAlignment="Center"    
  13.                     HorizontalAlignment="Center">    
  14.     
  15.             <!-- Text Box -->    
  16.             <Border x:Name="autoTextBoxBorder"    
  17.                         Width="220"    
  18.                         Height="50">    
  19.     
  20.                 <Border.Background>    
  21.                     <ImageBrush ImageSource="/WPFAutoCompleteTextBox;component/Content/img/text-box_bg.png"/>    
  22.                 </Border.Background>    
  23.     
  24.                 <TextBox x:Name="autoTextBox"    
  25.                              Width="220"     
  26.                              Height="50"    
  27.                              FontSize="18"      
  28.                              HorizontalAlignment="Center"     
  29.                              VerticalAlignment="Center"     
  30.                              BorderThickness="0"    
  31.                              VerticalContentAlignment="Center"    
  32.                              HorizontalContentAlignment="Center"    
  33.                              Padding="0,0,0,0"    
  34.                              Background="Transparent"    
  35.                              Foreground="Black"    
  36.                              TextChanged="AutoTextBox_TextChanged"/>    
  37.             </Border>    
  38.     
  39.             <!-- Auto Suggestion box -->    
  40.             <Popup x:Name="autoListPopup"    
  41.                    Visibility="Collapsed"                    
  42.                    Height="100"    
  43.                    StaysOpen="False"    
  44.                    Placement="Bottom">    
  45.     
  46.                 <ListBox x:Name="autoList"    
  47.                          Visibility="Collapsed"    
  48.                          Width="500"    
  49.                          Height="100"    
  50.                          SelectionChanged="AutoList_SelectionChanged" />    
  51.             </Popup>    
  52.         </StackPanel>    
  53.     </Grid>    
  54. </UserControl>    
In the above code, I have created my auto-complete/suggestion user control hierarchy from the built-in WPF control with default settings.
 
Step 3
 
Now, open the "Views\UserControls\AutoCompleteTextBoxUserControl.xaml.cs" file and replace with the following code.
  1. //-----------------------------------------------------------------------  
  2. // <copyright file="AutoCompleteTextBoxUserControl.xaml.cs" company="None">  
  3. //     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.  
  4. // </copyright>  
  5. // <author>Asma Khalid</author>  
  6. //-----------------------------------------------------------------------  
  7.   
  8. namespace WPFAutoCompleteTextBox.Views.UserControls  
  9. {  
  10.     using System;  
  11.     using System.Collections.Generic;  
  12.     using System.Linq;  
  13.     using System.Text;  
  14.     using System.Threading.Tasks;  
  15.     using System.Windows;  
  16.     using System.Windows.Controls;  
  17.     using System.Windows.Data;  
  18.     using System.Windows.Documents;  
  19.     using System.Windows.Input;  
  20.     using System.Windows.Media;  
  21.     using System.Windows.Media.Imaging;  
  22.     using System.Windows.Navigation;  
  23.     using System.Windows.Shapes;  
  24.   
  25.     /// <summary>  
  26.     /// Interaction logic for Autocomplete Text Box UserControl  
  27.     /// </summary>  
  28.     public partial class AutoCompleteTextBoxUserControl : UserControl  
  29.     {  
  30.         #region Private properties.  
  31.   
  32.         /// <summary>  
  33.         /// Auto suggestion list property.  
  34.         /// </summary>  
  35.         private List<string> autoSuggestionList = new List<string>();  
  36.  
  37.         #endregion  
  38.  
  39.         #region Default Constructor  
  40.   
  41.         /// <summary>  
  42.         /// Initializes a new instance of the <see cref="AutoCompleteTextBoxUserControl" /> class.  
  43.         /// </summary>  
  44.         public AutoCompleteTextBoxUserControl()  
  45.         {  
  46.             try  
  47.             {  
  48.                 // Initialization.  
  49.                 this.InitializeComponent();  
  50.             }  
  51.             catch (Exception ex)  
  52.             {  
  53.                 // Info.  
  54.                 MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);  
  55.                 Console.Write(ex);  
  56.             }  
  57.         }  
  58.  
  59.         #endregion  
  60.  
  61.         #region Protected / Public properties.  
  62.   
  63.         /// <summary>  
  64.         /// Gets or sets Auto suggestion list property.  
  65.         /// </summary>  
  66.         public List<string> AutoSuggestionList  
  67.         {  
  68.             get { return this.autoSuggestionList; }  
  69.             set { this.autoSuggestionList = value; }  
  70.         }  
  71.  
  72.         #endregion  
  73.  
  74.         #region Open Auto Suggestion box method  
  75.   
  76.         /// <summary>  
  77.         ///  Open Auto Suggestion box method  
  78.         /// </summary>  
  79.         private void OpenAutoSuggestionBox()  
  80.         {  
  81.             try  
  82.             {  
  83.                 // Enable.  
  84.                 this.autoListPopup.Visibility = Visibility.Visible;  
  85.                 this.autoListPopup.IsOpen = true;  
  86.                 this.autoList.Visibility = Visibility.Visible;  
  87.             }  
  88.             catch (Exception ex)  
  89.             {  
  90.                 // Info.  
  91.                 MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);  
  92.                 Console.Write(ex);  
  93.             }  
  94.         }  
  95.  
  96.         #endregion  
  97.  
  98.         #region Close Auto Suggestion box method  
  99.   
  100.         /// <summary>  
  101.         ///  Close Auto Suggestion box method  
  102.         /// </summary>  
  103.         private void CloseAutoSuggestionBox()  
  104.         {  
  105.             try  
  106.             {  
  107.                 // Enable.  
  108.                 this.autoListPopup.Visibility = Visibility.Collapsed;  
  109.                 this.autoListPopup.IsOpen = false;  
  110.                 this.autoList.Visibility = Visibility.Collapsed;  
  111.             }  
  112.             catch (Exception ex)  
  113.             {  
  114.                 // Info.  
  115.                 MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);  
  116.                 Console.Write(ex);  
  117.             }  
  118.         }  
  119.  
  120.         #endregion  
  121.  
  122.         #region Auto Text Box text changed the method  
  123.   
  124.         /// <summary>  
  125.         ///  Auto Text Box text changed method.  
  126.         /// </summary>  
  127.         /// <param name="sender">Sender parameter</param>  
  128.         /// <param name="e">Event parameter</param>  
  129.         private void AutoTextBox_TextChanged(object sender, TextChangedEventArgs e)  
  130.         {  
  131.             try  
  132.             {  
  133.                 // Verification.  
  134.                 if (string.IsNullOrEmpty(this.autoTextBox.Text))  
  135.                 {  
  136.                     // Disable.  
  137.                     this.CloseAutoSuggestionBox();  
  138.   
  139.                     // Info.  
  140.                     return;  
  141.                 }  
  142.   
  143.                 // Enable.  
  144.                 this.OpenAutoSuggestionBox();  
  145.   
  146.                 // Settings.  
  147.                 this.autoList.ItemsSource = this.AutoSuggestionList.Where(p => p.ToLower().Contains(this.autoTextBox.Text.ToLower())).ToList();  
  148.             }  
  149.             catch (Exception ex)  
  150.             {  
  151.                 // Info.  
  152.                 MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);  
  153.                 Console.Write(ex);  
  154.             }  
  155.         }  
  156.  
  157.         #endregion  
  158.  
  159.         #region Auto list selection changed method  
  160.   
  161.         /// <summary>  
  162.         ///  Auto list selection changed method.  
  163.         /// </summary>  
  164.         /// <param name="sender">Sender parameter</param>  
  165.         /// <param name="e">Event parameter</param>  
  166.         private void AutoList_SelectionChanged(object sender, SelectionChangedEventArgs e)  
  167.         {  
  168.             try  
  169.             {  
  170.                 // Verification.  
  171.                 if (this.autoList.SelectedIndex <= -1)  
  172.                 {  
  173.                     // Disable.  
  174.                     this.CloseAutoSuggestionBox();  
  175.   
  176.                     // Info.  
  177.                     return;  
  178.                 }  
  179.   
  180.                 // Disable.  
  181.                 this.CloseAutoSuggestionBox();  
  182.   
  183.                 // Settings.  
  184.                 this.autoTextBox.Text = this.autoList.SelectedItem.ToString();  
  185.                 this.autoList.SelectedIndex = -1;  
  186.             }  
  187.             catch (Exception ex)  
  188.             {  
  189.                 // Info.  
  190.                 MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);  
  191.                 Console.Write(ex);  
  192.             }  
  193.         }  
  194.  
  195.         #endregion  
  196.     }  

In the above code, I have created a public property "AutoSuggestionList" to which you will provide your auto-suggestion list.
I have, then, created an "OpenAutoSuggestionBox(..)" method which will open the auto suggestion box as the end-user types in the text box.
Then, I have created a "CloseSuggestionBox(...)" method which will close the auto-suggestion box when the end-user selects the target suggested item from the auto-suggestion list.
 
Then, I have created "AutoTextBox_TextChanged(...)" method which will update the auto-suggestion list according to the text typed in the text box by the end-user.
 
Finally, I have created "AutoList_SelectionChanged(...)" method which will update the text box according to the selected suggested item from the auto-suggestion list by the end-user.
 
Step 4
 
In order to use my autocomplete/suggestion text box control, you need to include my user control namespace into your target XAML file and the following line of code.
 
 
You also need to set your auto-suggestion list in the target XAML.CS file.
 
Step 5
 
Now, execute the project and you will be able to see the following in action.
 
 
 

Conclusion

 
In this article, we learned to create an auto-complete/auto-suggestion text box control using the built-in UI controls in the WPF platform. Along with this, we learned how to integrate this auto-complete/suggestion text box user control into our own target WPF page.
 
Disclaimer
 
The background image used in this article has been taken from freepike.