Warm tip: This article is reproduced from stackoverflow.com, please click
c# mvvm wpf xaml autocomplete

Textbox Autocomple/Autosuggestions

发布于 2020-04-05 00:26:13

Is it possible to add somehow autocomplete suggestions to textbox in a WPF application? Like where I bind the suggestions to a DataTable or List of Strings? Is this possible with a textbox?

 <TextBox Text="{Binding InputText, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                     HorizontalAlignment="Stretch"
                     VerticalAlignment="Stretch"
                     VerticalContentAlignment="Center" >
        <TextBox.InputBindings>
          <KeyBinding Command="{Binding EnterKeyPressedCommand}" Key="Return" />
        </TextBox.InputBindings>
      </TextBox>
Questioner
DataLordDev
Viewed
59
David Bentley 2020-01-31 23:20

If you are having trouble trying to find out where to start, there are actually several steps involved and likely SEVERAL ways to do this.

Off the top of my head, you could create a hidden ListBox that appears under your TextBox that contains your suggestions (make sure the ListBox sizes to content). As text changes, you can use a simple TestChanged event.

XAML:

<TextBox x:Name="someTextbox" 
    TextChanged="someTextbox_TextChanged"
</TextBox>

Code Behind:

    private void someTextbox_TextChanged(object sender, TextChangedEventArgs e)
    {
        // Call method to check for possible suggestions.
        // Display Listbox with suggested items.
    }

Then, clicking on an item in the Listbox would update the text.
NOTE: You will need some way to prevent the event from running logic when a user selects a suggestion form the ListBox

Now for MVVM:

private string _SomeTextbox = "";
public string SomeTextbox
{
    get { return _SomeTextbox; }
    set
    {
        _SomeTextbox = value;
        OnPropertyChanged(new PropertyChangedEventArgs("SomeTextbox"));

        // Call method to check for possible suggestions.
        // Display Listbox with suggested items.
    }
}

With MVVM, you can bind the ListBox visibility and content with relative ease and then display it as needed.

ANOTHER way to do this is to edit the TextBox default to have a built in ListBox. This path is WAY more complicated though.

Hope this gets you started.