[Sample of Mar 22th] Auto-complete textbox in WPF

 

Homepage image
Sample of the Day RSS Feed

Sample downloads
C# version:
https://code.msdn.microsoft.com/CSWPFAutoCompleteTextBox-08fe0116
VB version: https://code.msdn.microsoft.com/VBWPFAutoCompleteTextBox-1e4e9f56

Today’s code sample demonstrates how to achieve AutoCompleteTextBox in WPF Application.  To assist with data entry, Microsoft Internet Explorer 5 and later and some other browsers support a feature referred to as AutoComplete. AutoComplete monitors a TextBox and creates a list of values entered by the user. When the user returns to the text at a later time, the list is displayed. Instead of retyping a previously entered value, the user can simply select the value from this list.  In this example, we’ll create a TextBox that automatically completes input strings by comparing the prefix being entered to the prefixed of all strings in a maintained source. This is useful for TextBox controls in which URLs, addresses, file names, or commands will be frequently entered.

imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage https://1code.codeplex.com/.

 

Introduction

This example demonstrates how to achieve AutoCompleteTextBox in WPF Application.

To assist with data entry, Microsoft Internet Explorer 5 and later and some other browsers support a feature referred to as AutoComplete. AutoComplete monitors a TextBox and creates a list of values entered by the user. When the user returns to the text at a later time, the list is displayed. Instead of retyping a previously entered value, the user can simply select the value from this list.

In this example, we’ll create a TextBox that automatically completes input strings by comparing the prefix being entered to the prefixed of all strings in a maintained source. This is useful for TextBox controls in which URLs, addresses, file names, or commands will be frequently entered.

 

Running the Sample

Press F5 to run this application, and type some characters in test box, you will see following result.

image

 

Using the Code

1. Design the AutoCompleteEntry class which is used to represent a suggested item.

 Public Class AutoCompleteEntry 
    Inherits ComboBoxItem 
    Private tb As TextBlock 
 
 
    'text of the item  
    Private _text As String 
 
 
    ''' <summary>  
    ''' Contrutor of AutoCompleteEntry class  
    ''' </summary>  
    ''' <param name="text">All the Text of the item </param>  
    ''' <param name="bold">The already entered part of the Text</param>  
    ''' <param name="unbold">The remained part of the Text</param>  
    Public Sub New(ByVal text As String, ByVal bold As String, ByVal unbold As String) 
        _text = text 
        tb = New TextBlock() 
        'highlight the current input Text  
        tb.Inlines.Add(New Run() With {.Text = bold, .FontWeight = FontWeights.Bold, .Foreground = New SolidColorBrush(Colors.RoyalBlue)}) 
        tb.Inlines.Add(New Run() With {.Text = unbold}) 
        Me.Content = tb 
    End Sub 
 
 
    ''' <summary>  
    ''' Gets the text.  
    ''' </summary>  
    Public ReadOnly Property Text() As String 
        Get 
            Return _text 
        End Get 
    End Property 
End Class 

2. Design the AutoCompleteTextBox to Achieve AutoComplete TextBox or ComboBox.

 Public Class AutoCompleteTextBox 
    Inherits ComboBox 
    ''' <summary>  
    ''' Initializes a new instance of the <see cref="AutoCompleteTextBox"/> class.  
    ''' </summary>  
    Public Sub New() 
        'load and apply style to the ComboBox.  
        Dim rd As New ResourceDictionary() 
        rd.Source = New Uri("/" & Me.[GetType]().Assembly.GetName().Name & ";component/UserControls/AutoCompleteComboBoxStyle.xaml", UriKind.Relative) 
        Me.Resources = rd 
        'disable default Text Search Function  
        Me.IsTextSearchEnabled = False 
    End Sub 
 
    ''' <summary>  
    ''' override OnApplyTemplate method  
    ''' get TextBox control out of Combobox control, and hook up TextChanged event.  
    ''' </summary>  
    Public Overloads Overrides Sub OnApplyTemplate() 
        MyBase.OnApplyTemplate() 
        'get the textbox control in the ComboBox control  
        Dim textBox As TextBox = TryCast(Me.Template.FindName("PART_EditableTextBox", Me), TextBox) 
        If textBox IsNot Nothing Then 
            'disable Autoword selection of the TextBox  
            textBox.AutoWordSelection = False 
            'handle TextChanged event to dynamically add Combobox items.  
            AddHandler textBox.TextChanged, AddressOf textBox_TextChanged 
        End If 
    End Sub 
 
    'The autosuggestionlist source.  
    Private _autoSuggestionList As New ObservableCollection(Of String)() 
 
    ''' <summary>  
    ''' Gets or sets the auto suggestion list.  
    ''' </summary>  
    ''' <value>The auto suggestion list.</value>  
    Public Property AutoSuggestionList() As ObservableCollection(Of String) 
        Get 
            Return _autoSuggestionList 
        End Get 
        Set(ByVal value As ObservableCollection(Of String)) 
            _autoSuggestionList = value 
        End Set 
    End Property 
 

    ''' <summary>  
    ''' main logic to generate auto suggestion list.  
    ''' </summary>  
    ''' <param name="sender">The source of the event.</param>  
    ''' <param name="e">The <see cref="System.Windows.Controls.TextChangedEventArgs"/>  
    ''' instance containing the event data.</param>  
    Private Sub textBox_TextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs) 
        Dim textBox As TextBox = TryCast(sender, TextBox) 
        textBox.AutoWordSelection = False 
        ' if the word in the textbox is selected, then don't change item collection  
        If (textBox.SelectionStart <> 0 OrElse textBox.Text.Length = 0) Then 
            Me.Items.Clear() 
            'add new filtered items according the current TextBox input  
            If Not String.IsNullOrEmpty(textBox.Text) Then 
                For Each s As String In Me._autoSuggestionList 
                    If s.StartsWith(textBox.Text, StringComparison.InvariantCultureIgnoreCase) Then 
 
                        Dim unboldpart As String = s.Substring(textBox.Text.Length) 
                        Dim boldpart As String = s.Substring(0, textBox.Text.Length) 
                        'construct AutoCompleteEntry and add to the ComboBox  
                        Dim entry As New AutoCompleteEntry(s, boldpart, unboldpart) 
                        Me.Items.Add(entry) 
                    End If 
                Next 
            End If 
        End If 
        ' open or close dropdown of the ComboBox according to whether there are items in the  
        ' fitlered result.  
        Me.IsDropDownOpen = Me.HasItems 
 
        'avoid auto selection  
        textBox.Focus() 
 
        textBox.SelectionStart = textBox.Text.Length 
    End Sub 
End Class 

3. Set the style of the AutoCompleteTextBox in Xaml .

4. Set the suggested source for the AutoCompleteTextBox.

 Private Sub ConstructAutoCompletionSource() 
 
 
    Me.textBox.AutoSuggestionList.Add("Hello world") 
    Me.textBox.AutoSuggestionList.Add("Hey buddy") 
    Me.textBox.AutoSuggestionList.Add("Halo world") 
    Me.textBox.AutoSuggestionList.Add("apple") 
    Me.textBox.AutoSuggestionList.Add("apple tree") 
    Me.textBox.AutoSuggestionList.Add("appaaaaa") 
    Me.textBox.AutoSuggestionList.Add("arrange") 
    For i As Integer = 0 To 99 
        Me.textBox.AutoSuggestionList.Add("AA" & i) 
    Next 
End Sub 

 

More Information

ComboBox Class

https://msdn.microsoft.com/en-us/library/system.windows.controls.combobox.aspx

FrameworkElement.OnApplyTemplate Method

https://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.onapplytemplate.aspx