AutoComplete TextBox in WPF

Viewed 121195

Is it possible to make a textbox autocomplete in WPF?

I found a sample where a combo box is used and the triangle is removed by editing the style template.

Is there a better solution?

7 Answers

If you have a small number of values to auto complete, you can simply add them in xaml. Typing will invoke auto-complete, plus you have dropdowns too.

<ComboBox Text="{Binding CheckSeconds, UpdateSourceTrigger=PropertyChanged}"
          IsEditable="True">
    <ComboBoxItem Content="60"/>
    <ComboBoxItem Content="120"/>
    <ComboBoxItem Content="180"/>
    <ComboBoxItem Content="300"/>
    <ComboBoxItem Content="900"/>
</ComboBox>

I'm surprised why no one suggested to use the WinForms Textbox.

XAML:

     <WindowsFormsHost  Margin="10" Width="70">
        <wf:TextBox x:Name="textbox1"/>
     </WindowsFormsHost>

Also don't forget the Winforms Namespace:

xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

C#:

     AutoCompleteStringCollection stringCollection = new AutoCompleteStringCollection(){"String 1", "String 2", "etc..."};
   
     textbox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
     textbox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
     textbox1.AutoCompleteCustomSource = stringCollection;

With Autocomplete, you need to do it in the Code behind, because for some reasons, others might can explain, it throws an exception.

Here a way by using WPF PopUp element with a textBox :

XAML file

<TextBox x:Name="DocumentType"
    Margin="20"
    KeyUp="DocumentType_KeyUp"
    LostFocus="DocumentType_LostFocus"/>

<Popup x:Name="autoCompletorListPopup"
        Visibility="Collapsed"
        StaysOpen="False"
        AllowsTransparency="True"
        PlacementTarget="{Binding ElementName=DocumentType}"
        Width="150"
        Placement="Bottom">
    <ListBox x:Name="autoCompletorList"
                Background="WhiteSmoke"
                MaxHeight="200"
                Margin="20 0"
                SelectionChanged="autoCompletorList_SelectionChanged"/>
</Popup>

CS file

List<string> listDocumentType = new List<string>() {"Pdf File","AVI File","JPEG file","MP3 sound","MP4 Video"} //...

private void autoCompletorList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    try
    {
        if (autoCompletorList.SelectedItem != null)
        {
            DocumentType.Text = autoCompletorList.SelectedValue.ToString();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private void DocumentType_KeyUp(object sender, KeyEventArgs e)
{
    try
    {
        if(e.Key == Key.Enter)
        {
            // change focus or remove focus on this element
            NextElementBox.Focus();
        }
        else
        {
            if (DocumentType.Text.Trim() != "")
            {
                autoCompletorListPopup.IsOpen = true;
                autoCompletorListPopup.Visibility = Visibility.Visible;
                autoCompletorList.ItemsSource = listDocumentType.Where(td => td.Trim().ToLower().Contains(DocumentType.Text.Trim().ToLower()));
            }
            else
            {
                autoCompletorListPopup.IsOpen = false;
                autoCompletorListPopup.Visibility = Visibility.Collapsed;
                autoCompletorList.ItemsSource = null;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private void DocumentType_LostFocus(object sender, RoutedEventArgs e)
{
    try
    {
        if (autoCompletorList.SelectedItem != null)
        {
            DocumentType.Text = autoCompletorList.SelectedValue.ToString();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
Related